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.
這道題在單鏈表的反轉上做了一點點的修改,要求只反轉鏈表的從第m個到第n個結點。分兩步走:
1. 定位到第m個結點
2. 進行反轉直到第n個結點:沒遇到一個結點,就把它插入到第m個結點的前面的位置,然後繼續下一個結點。
在操作的過程中需要注意:
1. 需要一個指向第m個結點前驅結點的指針
2. 若m==n,則無需操作。
下面貼上代碼:
/**
* 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;
}
};