Merge two sorted lists
Merge two sorted linked lists and return it as a new list. The new list shoshould be made by splicing together the nodes of the first two lists.
Algorithm ideas:
Based on L1, L2 points are inserted into L1 one by one. The two linked lists are traversed once. I have not optimized the time complexity O (m + n ), space complexity O (1)
1 public class solution {2 Public listnode mergetwolists (listnode L1, listnode l2) {3 if (L1 = NULL) return L2; 4 If (L2 = NULL) return L1; 5 listnode head = new listnode (1); 6 head. next = L1; 7 listnode pre = head; 8 listnode node = L2; 9 While (L2! = NULL) {10 node = L2; 11 while (PRE. Next! = NULL & pre. next. val <= node. val) {12 pre = pre. next; 13} 14 L2 = node. next; 15 node. next = pre. next; 16 pre. next = node; 17 pre = node; // if this sentence is deleted, L2 scans both sides, L1 scans again, but the time complexity remains unchanged 18} 19 Return head. next; 20} 21}