[LeetCode] 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 list.
This problem is slightly modified on the reverse of a single-chain table, requiring that only the chain table be reversed from the m to the n node. Take two steps:
1. Locate the m Node
2. Reverse until the nth node: If a node is not met, insert it to the front of the m node and continue to the next node.
Note the following during the operation:
1. A pointer pointing to the first m node is required.
2. If m = n, no operation is required.
Paste the code below:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *reverseBetween(ListNode *head, int m, int n) { if (m == n) return head; ListNode* first = new ListNode(0); int len = n - m; first->next = head; ListNode* p = first; while (p&&m > 1){ p = p->next; m--; } ListNode* q = p->next; ListNode* tail = q; p->next = NULL; ListNode* r = NULL; while (q&&len >= 0){ r = q->next; q->next = p->next; p->next = q; q = r; len--; } tail->next = r; return first->next; }};