LeetCode OJ Linked List: 92 questions, 143 questions, 147 questions and 160 questions, leetcodeoj
Question 92:Reverse Linked List II
Question Analysis:First Thought: Find the precursor of m and the successor of n, record it, disconnect m to n, reverse it, And then reconnect. The second approach is to re-insert m to n to the front of m. Careful boundary.
First thought:
1 class Solution {2 public: 3 ListNode * reverseList (ListNode * head) 4 {5 if (head = NULL | head-> next = NULL) 6 {7 return head; 8} 9 10 ListNode * cur = head, * pre = NULL, * next = head-> next; 11 for (; cur! = NULL; pre = cur, cur = next, next = next? Next-> next: NULL) 12 {13 cur-> next = pre; 14} 15 16 return pre; 17} 18 19 ListNode * reverseBetween (ListNode * head, int m, int n) 20 {21 if (head = NULL | head-> next = NULL | m = n) 22 {23 return head; 24} 25 26 ListNode tmpNode (-1); 27 tmpNode. next = head; 28 29 int k = 1; 30 ListNode * prem = & tmpNode, * curm = head; 31 ListNode * curn = head, * nextn = curn-> next; 32 for (; k <m; ++ k) 33 {34 prem = curm; 35 curm = curm-> next; 36 curn = curn-> next; 37} 38 for (; k <n; ++ k) 39 {40 curn = curn-> next; 41} 42 nextn = curn-> next; 43 44 45 curn-> next = NULL; 46 ListNode * tmp = reverseList (curm); 47 prem-> next = tmp; 48 curm-> next = nextn; 49 50 return tmpNode. next; 51} 52 };View Code
The second approach:
1 class Solution 2 {3 public: 4 ListNode * reverseBetween (ListNode * head, int m, int n) 5 {6 ListNode dummy (-1); 7 dummy. next = head; 8 ListNode * prev = & dummy; 9 for (int I = 0; I <m-1; ++ I) 10 {11 prev = prev-> next; 12} 13 14 ListNode * const head2 = prev; 15 prev = head2-> next; 16 ListNode * cur = prev-> next; 17 for (int I = m; I <n; ++ I) 18 {19 prev-> next = cur-> next; 20 cur-> next = head2-> next; 21 head2-> next = cur; // insert header 22 cur = prev-> next; 23} 24 25 return dummy. next; 26} 27 };View Code
Question 143:Reorder List
Question Analysis:Split from the middle, the second segment is reversed, and inserted in turn with the first segment.
View Code
Question 147:Insertion Sort List
Question Analysis:Insert and sort directly, which is simple and crude.
View Code
Question 160:Intersection of Two Linked Lists
Question Analysis:K = length of the long chain table-length of the short chain table, and then the long chain table goes k steps first, and the long chain table goes together until it is intersecting.
View Code
Other questions about LeetCode OJ:
LeetCode OJ Linked List: 24 questions, 148 questions, and 61 questions