Merge Sorted Lists
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 .
Solution:
Linked list in the merge when in fact to have an advantage, it does not need extra space, do not want to array, to open a space to put an array. The operation is also very simple, get a dummy, and then the small directly connected to the line. This is a basic operation and can be used as a function call in other questions.
Code:
/*** Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) {* This.val = val; * This.next = null; * } * } */ Public classSolution {/** * @paramListNode L1 is the head of the linked list *@paramListNode L2 is the head of the linked list *@return: ListNode head of linked list*/ PublicListNode mergetwolists (listnode L1, ListNode L2) {if(L1 = =NULL){ returnL2; } if(L2 = =NULL){ returnL1; } ListNode Dummy=NewListNode (0); ListNode node=dummy; while(L1! =NULL&& L2! =NULL){ if(L1.val <l2.val) {Node.next=NewListNode (L1.val); L1=L1.next; Node=Node.next; } Else{Node.next=NewListNode (L2.val); L2=L2.next; Node=Node.next; } } while(L1! =NULL) {Node.next=NewListNode (L1.val); L1=L1.next; Node=Node.next; } while(L2! =NULL) {Node.next=NewListNode (L2.val); L2=L2.next; Node=Node.next; } returnDummy.next; }}View Code
[Lintcode] Merge Sorted Lists