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.
Ideas:
- Set two head pointers, one pointer fixed, to return the last header, a pointer to organize the node order, traverse the two linked lists, each pointing to a small node
public class Mergetwosortedlists {public class ListNode {int val; ListNode Next; ListNode (int x) {val = x; next = null;}} Public ListNode mergetwolists (listnode L1, ListNode L2) { ListNode h1 = new ListNode (0), H2 = H1;while (L1!=null && Amp L2!=null) {if (L1.val < l2.val) {H1.next = L1;L1 = L1.next;} Else{h1.next = L2;l2 = L2.next;} H1 = H1.next;} if (L1 = = null) {h1.next = L2;} if (L2 = = null) {h1.next = L1;} return h2.next;} }
- There is also a more cock method, recursive, and the smallest node is selected each time, but the code is more concise
Recursive method, the head pointer points to the smallest node in two lists at a time, and then recursively public listnode mergetwolists (listnode L1, ListNode L2) { if (L1 = null) return l2;if ( L2 = = null) return L1; ListNode h;if (L1.val < l2.val) {h = L1;h.next = Mergetwolists (L1.next, L2);} else{h = L2;h.next = mergetwolists (L1, l2.next);} return h;}
Leetcode | #21 Merge Sorted Lists