Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
Problem Solving Ideas:
The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them was empty, simply append it to the merged list, since it was already sorted.
Who put who in the small.
Java Code:
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {ListNode Fakehead=NewListNode (0); ListNode P=Fakehead; ListNode P1= L1, p2 =L2; while(p1!=NULL&& P2! =NULL) { if(P1.val <=p2.val) {P.next=P1; P1=P1.next; }Else{P.next=P2; P2=P2.next; } P=P.next; } if(P1! =NULL) {P.next=P1; } if(P2! =NULL) {P.next=P2; } returnFakehead.next; }}
20160601:
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {ListNode dummy=NewListNode (0); ListNode cur=dummy; while(L1! =NULL&& L2! =NULL) { if(L1.val <=l2.val) {Cur.next=L1; L1=L1.next; } Else{Cur.next=L2; L2=L2.next; } cur=Cur.next; } if(L1! =NULL) {Cur.next=L1; } if(L2! =NULL) {Cur.next=L2; } returnDummy.next; }}
Reference:
1. http://www.programcreek.com/2012/12/leetcode-merge-two-sorted-lists-java/
Leetcode 21. Merge Sorted Lists