https://leetcode.com/problems/merge-two-sorted-lists/#/description
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.
覃超:clarification:問是不是sorted
寫程序第一步永遠永遠先判斷valid parameters
Mar 21,2017 Version:
Today I wrote this question again. This time I understand ** fakehead ** better.
The key is to think clearly about the while clause and the '&&' symbol in it.
/**
* Assume there's a testcase:
* l1 : 1->3->5->7
* l2 : 2->4
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode res = new ListNode(-1);
ListNode fakeHead = res;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
res.next = l1;
res = res.next;
l1 = l1.next;
} else {
res.next = l2;
res = res.next;
l2 = l2.next;
}
}
if (l1 != null) {
res.next = l1;
} else {
res.next = l2;
}
return fakeHead.next;
}
I also found a recursive version in the solutions:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode mergeHead;
if(l1.val < l2.val){
mergeHead = l1;
mergeHead.next = mergeTwoLists(l1.next, l2);
}
else{
mergeHead = l2;
mergeHead.next = mergeTwoLists(l1, l2.next);
}
return mergeHead;
}
Mar1 Version:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode fakeHead = new ListNode(0);
//pointer是fakeHead對象的引用忽媒,以后的操作都在fakehead上
ListNode pointer = fakeHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
pointer.next = l1;
l1 = l1.next;
} else {
pointer.next = l2;
l2 = l2.next;
}
//注意這一行蟹漓,如果不加,pointer就一直停留在原地了
pointer = pointer.next;
}
if (l1 != null) {
pointer.next = l1;
} else {
pointer.next = l2;
}
return fakeHead.next;
}