Topic:
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.
Translation:
Connect 2 ordered linked lists and return a new linked list
Ideas:
It is simple to iterate over each node, and the small words are added behind the new list. If one is empty, the other is connected to the end of the new list.
The second idea is to use a list as the benchmark, and then compare with the other, if the L2 node value is less than this, then the L2 node is inserted, and then L2 backward move one bit.
Code Listing 1:
Public static ListNode mergetwolists (ListNode L1, ListNode L2) { ListNode root = new ListNode (0); ListNode pre = root; Pre.next = L1; while (L1!=null && l2!=null) { if (L1.val > L2.val)//@1 { ListNode next = l2.next; L2.next = Pre.next; Pre.next = L2; L2 = Next; Pre = Pre.next; } else { L1 = l1.next; Pre = Pre.next; } } if (L1 = = null) { pre.next = L2; } return root.next; }
@1 first saves the next node of the L2, then inserts the L2 node into the L1, and finally points the L2 to the node you just saved.
Code Listing 2:
Public static ListNode mergetwolists (ListNode L1, ListNode L2) { ListNode root = new ListNode (0); ListNode pre = root; Pre.next = L1; while (true) { if (L1 = = null) { pre.next = L2; break; } if (L2 = = null) { pre.next = L1; break; } if (L1.val < L2.val) { pre.next = L1; L1 = L1.next; } else { Pre.next = L2; L2 = L2.next; } Pre = Pre.next; } return root.next; }
Code 2 is easier to understand. It's not a lot to explain.
Leetcode Merge two Sorted Lists connect the two linked lists in order