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.
思路:其实如果你会one pass的就地逆序,就会做这道题。 in place and one pass reverse , a little confused。但是必须掌握!
这道题利用的是指针gap和one-pass & in-place逆序问题。
如下,
/** * 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; int offset=n-m; ListNode *pHead = new ListNode(0); pHead->next=head; ListNode *pre=pHead; while(--m){ pre=pre->next; } ListNode *pstart=pre->next; ListNode *p; while(offset--){ p=pstart->next; pstart->next=p->next; p->next=pre->next; pre->next=p; } return pHead->next; } };