Title Link: Reverse Linked List II
Reverse a linked list from position m to N. Do it in-place and in One-pass.
For example:
Given 1->2->3->4->5->null, M = 2 and n = 4,
Return 1->4->3->2->5->null.
Note:
Given m, n satisfy the following condition:
1≤m≤n≤length of the list.
The requirement of this problem is to reverse the M-n position in the list.
chain list processing, first add an empty table header, easy to handle. The l pointer is then moved to the front of the m position so that R moves to the M position, which constantly inserts the nodes behind R into the L until the n position.
Assuming m=2,n=4, the linked list is: Head--1, 2, 3, 4, 5---------0--1, 2 5. Null to move the L pointer to the M position before moving R to the m position, i.e., 0, 1, 2 | | L The node behind the RR is inserted into the back of L: listnode *temp = L--next:h, 0, 1, 2, 3, 4 ^ | | L TEMP, R L-next = R-Next: |-------->|h, 0, 1 2, 3, 4 ^ ^ | | L TEMP, rr-next = Next Next: |-------->|h, 0, 1 2 3, 4, 5, NULL ^ |-------->| | ^ L | Temp, RL, next, Next = temp: |-------->|h, 0, 1 2 <-3 4, 5--NULL ^ |-------->| | ^ L | Temp, R: 1, 0, H--3-> 2, 4, 5, NULL ^ ^ | | L R then continue to insert the R back node behind L, and so on, loop ...
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {3 Public:4 ListNode *Reversebetween(ListNode *Head, int m, int N)5 {6 ListNode *h = New ListNode(0);7 h - Next = Head;8 9 ListNode *L = h, *R;Ten for(int I = 1; I < m; ++ I) One L = L - Next; A - R = L - Next; - for(int I = 1; I < N - m + 1; ++ I) the { - ListNode *Temp = L - Next; - L - Next = R - Next; - R - Next = R - Next - Next; + L - Next - Next = Temp; - } + A return h - Next; at } - };
Reprint please indicate source: Leetcode---92. Reverse Linked List II
Leetcode---92. Reverse Linked List II