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.
//#92 Reverse Linked List II
//4ms 94.89%
#include <iostream>
using namespace std;
class Solution
{
public:
ListNode* reverseBetween(ListNode* head, int m, int n)
{
int size(0);
ListNode *sizer(head);
while(sizer != NULL)
{
size ++;
sizer = sizer->next;
}
//cout << "Size of this linked list is " << size << endl;
//cout << "After Reverse: ";
if(m==n) return head;
//this if includes two cases: size == 0 size == 1
//after this, m != n at all times
if(head->next->next == NULL)
//size == 2, m == 1, n == 2 only case
//treat it as a normal reverse_linked_list
{
head->next->next = head;
head = head->next;
head->next->next = NULL;
return head;
}
//size >= 3
//4 cases
//
ListNode *m_p, *n_p;
m_p = head;
if(m != 1)
{
for(int i=0; i<m-2; i++)
{
m_p = m_p->next;
}
}
if(n == size)
{
n_p = NULL;
}
else
{
n_p = head;
for(int i=0; i<n-1; i++)
{
n_p = n_p->next;
}
ListNode *tmp;
tmp = n_p->next;
n_p->next = NULL;
n_p = tmp;
}
//m_p and n_p should be reserved for use after sub-reverse
ListNode *sub_head;
if(m == 1)
{
sub_head = head;
}
else
{
sub_head = m_p->next;
}
//now should also consider if this sub linked list has a size of 2 or 3 and more
//cout << "m_p == " << m_p->val << ", ";
//if(n_p == NULL) cout << "n_p == NULL\n";
//else cout << "n_p == " << n_p->val << endl;
//cout << "sub_head == " << sub_head->val << endl;
if(sub_head->next->next == NULL) //sub linked_list size == 2
{
//cout << "sub linked_list == 2\n";
sub_head->next->next = sub_head;
sub_head = sub_head->next;
sub_head->next->next = n_p;
if(m==1) head = sub_head;
else m_p->next = sub_head;
return head;
}
ListNode *previous_p, *current_p, *next_p;
//cout << "sub linked_list size >= 3 \n";
previous_p = sub_head;
current_p = sub_head->next;
next_p = sub_head->next->next;
//cout << "previous_p == " << previous_p->val << ", current_p == " << current_p->val << ", next_p == " << next_p->val << endl;
previous_p->next = n_p;
while(next_p->next != NULL)
//next_p reaching the tail and when jumping out of this while loop
//next_p->next == NULL
{
current_p->next = previous_p;
//prepare for next round
previous_p = current_p;
current_p = next_p;
next_p = next_p->next;
}
current_p->next = previous_p;
next_p->next = current_p;
sub_head = next_p;
if(m==1) head = sub_head;
else m_p->next = sub_head;
return head;
}
};