"021-merge two Sorted Lists (combined with two sequential single-linked lists)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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.
Main Topic
Merges two sorted lists and returns a new list. The result of the new linked list consists of the original two linked list nodes, which means that the linked list cannot contain the newly created nodes.
Thinking of solving problems
Use the head node root for auxiliary operations, create a head node, and then use two references to the head node of the two linked list, the node of the smaller node value is taken down to the end of the root list, while the picked link head reference to move to the next node, the operation, to the original two linked list of one is empty, Finally, the remaining nodes are then connected to the end of the root list. Finally, the next node of root is returned, which is the new list header.
Code Implementation
Linked list Node class
publicclass ListNode { int val; ListNode next; ListNode(int x) { val = x; null; }}
Algorithm implementation class
Public classSolution { PublicListNodemergetwolists(ListNode L1, ListNode L2) {ListNode head =NewListNode (0);//Create a head node and remove it at the end .ListNode tail = head; while(L1! =NULL&& L2! =NULL) {if(L1.val <= L2.val) {tail.next = L1; L1 = L1.next; }Else{tail.next = L2; L2 = L2.next; } tail = Tail.next;//move to a new tail node} Tail.next = (L1! =NULL? L1:L2);returnHead.next;//Head next node is the first Data node.}}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47016121"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "021-merge two Sorted Lists (merge two ordered single linked list)"