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.
/**
* 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(head == NULL || head->next == NULL || m > n || m < 1 || n < 1)
return head;
ListNode* insertp = NULL;//表示所需要插入节点的位置
int count = 1;//计数器,从m到n
ListNode* curr = head;
while(curr != NULL && count < m)
{
insertp = curr;
curr = curr->next;
count++;
}
if(curr == NULL)
return head;
//curr记住了m所在的位置,接下来从m-n之间将所有nodes reverse
ListNode* pre = curr;
curr = curr->next;
count ++;
while(curr != NULL && count <= n)
{
if(insertp == NULL)//反复往头结点插入
{
ListNode* tmp2 = curr->next;
ListNode* tmp = head;
head = curr;
head->next = tmp;
pre->next = tmp2;
curr = tmp2;
count++;
continue;
}
//put curr to [insertp, insertp->next]
ListNode* tmp2 = curr->next;
ListNode* tmp = insertp->next;
insertp->next = curr;
curr->next = tmp;
//delete curr
pre->next = tmp2;
curr = tmp2;
count++;
}
return head;
}
};