leetcode-21. Merge Two Sorted Lists
题目:
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.
思路就是先对所有节点前面加一个哑节点。然后根据哑节点的next一个一个转移到最终的节点后。另外需要处理一下最后只有一个队列剩余的情况。
/**
* 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) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode d1 = new ListNode(0);
ListNode d2 = new ListNode(0);
ListNode ret = new ListNode(0);
ListNode tmp = ret;
d1.next = l1;
d2.next = l2;
while(d1.next != null && d2.next != null){
if(d1.next.val < d2.next.val){
tmp.next = d1.next;
d1.next = d1.next.next;
}else{
tmp.next = d2.next;
d2.next = d2.next.next;
}
tmp = tmp.next;
}
if(d2.next != null) d1.next =d2.next;
tmp.next = d1.next;
return ret.next;
}
}