* Reverse Linked List II*
Description
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.
Analysis
这道题的意思其实是从链表中取出其中的一段来进行倒置。
我认为难度就在于它是要先将其中一段倒置之后重新放回链表中形成新的链表。
我的第一种做法其实就是先将要倒置的链表段的起点和终点取出来,然后将改链表段倒置再接回去。
可是这个做法超时了。
所以我最后ac的做法就是先找到链表段的起点,然后从起点开始,到终点结束,将该链表段倒置。
需要注意的一点是要记录边界点的位置。
Code
/**
* 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 * res = new ListNode(-1);
res->next = head;
ListNode * index = res;
for(int i=1;i<=m-1;++i) index = index->next;
ListNode *pre = index;
ListNode *local = index->next;
ListNode *front;
for(int i=m;i<=n;++i){
index = pre->next;
pre->next = index->next;
index->next = front;
front = index;
}
index = pre->next;
pre->next = front;
local->next = index;
return res->next;
}
};