Merge Sorted Lists
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.
Idea: Merge two sorted single-linked lists. The algorithm is relatively simple, similar to the merge sort. Just the data structure on the previous learning, now forget more, write the first time more laborious. and want to repeat the code to write the method, but the method can not change the value of parameters synchronously, there is no way, the first time to try to be accurate, first a over again.
The code is a bit messy, but it's easier to understand. As follows:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x;}}} */public class Soluti On {public ListNode mergetwolists (listnode L1, ListNode L2) {ListNode head = null; ListNode p = null; From small to large sequential merge list while (L1! = null && L2! = null) {if (L1.val > L2.val) {if (head = = nul L) {head = P = L2; }else{p.next = L2; p = p.next; } L2 = L2.next; }else{if (head = = null) {head = P = L1; }else{p.next = L1; p = p.next; } L1 = L1.next; }}//If there is data in the list, continue merging, the following is a maximum of only one linked list with data while (L1! = null) {if (head = = null) {head = P = L1; }else{p.next = L1; p = p.next; } L1 = L1.next; } while (L2! = null) {if (head = =NULL) {head = P = L2; }else{p.next = L2; p = p.next; } L2 = L2.next; } p = null; return head; }}
Smooth a after thinking about streamlining the code, because the above code looks really uncomfortable, online reference some information, inspired to write the following code.
PS: Two codes have the same effect.
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public listnode mergetwolists (listnode L1, ListNode L2) { if (L1 = null | | l2 = NULL) return L1 = null ? L2:L1; ListNode head = new ListNode (0);//define a head node listnode p = head; ListNode temp = null; while (L1 = null && L2! = null) { if (L1.val > L2.val) { temp = l2;//with a temp save now L1 or L2 L2 = L2.next The//L1 or L2 pointer moves back 1 bits }else{ temp = L1; L1 = L1.next; } Exchange data P.next = temp; p = p.next; } Temp takes one that is not empty (or it may be all empty) temp = L1 = = null? l2:l1; P.next = temp;//All the remaining links (the method above is too verbose) return to Head.next; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 21.Merge Sorted Lists (combined sort list) thinking and method of solving problems