关闭

(Java)LeetCode-21. Merge Two Sorted Lists

72人阅读 评论(0) 收藏 举报
分类:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.


这道题和之前的合并已排序的数组的思路一样的,就是变成了链表而已,稍稍复杂一点。


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode list = new ListNode(-2);
        ListNode head = list;
        
        while(l1 != null || l2 != null){
        	if(l1 == null){
        		list.next = l2;
        		return head.next;
        	}else if( l2 == null){
        		list.next = l1;
        		return head.next;
        	}else if(l1.val >= l2.val){
        		ListNode next = new ListNode(l2.val);
        		list.next = next;
        		list = next;
        		l2 = l2.next;
        	}else{
        		ListNode next = new ListNode(l1.val);
        		list.next = next;
        		list = next;
        		l1 = l1.next;
        	}
        }
		return head.next;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:15029次
    • 积分:1055
    • 等级:
    • 排名:千里之外
    • 原创:96篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论