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.
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head == NULL || head->next == NULL || m == n) return head;
if(n<m) return NULL;
ListNode * p = head;
ListNode * tmp_head = new ListNode(0);
tmp_head->next = p;
ListNode * pre = tmp_head;
int count = m - 1;
while(count&&p)
{
pre = p;
p = p->next;
--count;
}
if (p == NULL) return NULL;
count = n-m;
ListNode * next_node = p->next;
ListNode * first_reverse_node = p ;
while(count&&next_node)
{
cout<<next_node->val<<"##"<<endl;
ListNode * tmp = pre->next;
ListNode * next = next_node->next;
pre->next = next_node;
first_reverse_node->next = next; 这一步很重要
next_node->next = tmp;
next_node = next;
--count;
}
return tmp_head->next;
}
};