题目描述
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given1->2->3->4->5->NULL, m = 2 and n = 4,
return1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
上面就完成了s->r->q的转变,以此类推
/**
* 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) {
ListNode L = ListNode(0);
L.next = head;
ListNode *p = &L;
ListNode *q = head;
for(int i=1;i<m;i++)
{
p = q;
q = q->next;
}
for(int i=0;i<n-m;i++)
{
ListNode *t = q->next;
q->next = t->next;
t->next = p->next;
p->next = t;
}
return L.next;
}
};