Question: 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.
Personal thoughts:
1. merge two ordered linked lists. Generally, we use the merge method to set a pointer for the traversal chain table, compare the node size one by one, and use the small node as the next node of the new linked list, then let the pointer of the small node go one step backward until a linked list is completed.
2. When a linked list is completed, the rest of the other linked list is connected to the back of the new linked list.
Code:
1 # include <stddef. h> 2 3 struct listnode 4 {5 Int val; 6 listnode * Next; 7 listnode (int x): Val (x), next (null) {}; 8 }; 9 10 class solution11 {12 public: 13 listnode * mergetwolists (listnode * L1, listnode * l2) 14 {15 // If L1 or L2 is null 16 if (! L1) 17 {18 return L2; 19} 20 if (! L2) 21 {22 return L1; 23} 24 25 listnode * cur_l1 = L1; 26 listnode * cur_l2 = L2; 27 listnode * head_new = NULL; 28 listnode * cur_new = NULL; 29 30 While (cur_l1 & cur_l2) 31 {32 If (cur_l1-> Val <= cur_l2-> Val) 33 {34 if (! Cur_new) 35 {36 head_new = cur_new = cur_l1; 37} 38 else39 {40 cur_new-> next = cur_l1; 41 cur_new = cur_new-> next; 42} 43 cur_l1 = cur_l1-> next; 44} 45 else46 {47 If (! Cur_new) 48 {49 head_new = cur_new = cur_l2; 50} 51 else52 {53 cur_new-> next = cur_l2; 54 cur_new = cur_new-> next; 55} 56 cur_l2 = cur_l2-> next; 57} 58} 59 60 if (! Cur_l1) 61 {62 while (cur_l2) 63 {64 cur_new-> next = cur_l2; 65 cur_new = cur_new-> next; 66 cur_l2 = cur_l2-> next; 67} 68} 69 70 If (! Cur_l2) 71 {72 while (cur_l1) 73 {74 cur_new-> next = cur_l1; 75 cur_new = cur_new-> next; 76 cur_l1 = cur_l1-> next; 77} 78} 79 80 return head_new; 81} 82}; 83 84 int main () 85 {86 return 0; 87}
View code
This idea is basically the same on the Internet and is a basic topic.