Description
Merge sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should is made by splicing together the nodes of the and lists in sorted order.
Example
Given 1->3->8->11->15->null
, 2->null
return 1->2->3->8->11->15->null
.
Problem solving: A classic topic, the merger of ordered lists. The Lintcode list does not have a head pointer by default, but it can construct a list of lead nodes to store the results, and then remove the head node when returning. The code is as follows:
/*** Definition for ListNode * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public classSolution {/** * @paramL1:listnode L1 is the head of the linked list *@paramL2:listnode L2 is the head of the linked list *@return: ListNode head of linked list*/ PublicListNode mergetwolists (listnode L1, ListNode L2) {//Write your code hereListNode Nhead =NewListNode (0); ListNode Rear=Nhead; while(L1! =NULL&& L2! =NULL){ if(L1.val <l2.val) {Rear.next=L1; L1=L1.next; }Else{Rear.next=L2; L2=L2.next; } Rear=Rear.next; Rear.next=NULL; } if(L1! =NULL) {Rear.next=L1; }Else{Rear.next=L2; } returnnhead.next;//Key}}
165. Merge Sorted Lists "Lintcode by Java"