#include <cstddef>
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *reverseBetween(ListNode *head, int m, int n) {
if (m >= n || head==NULL) {
return head;
}
int length =0;
ListNode* pHead = head;
while(pHead) {
length++;
pHead=pHead->next;
}
if (m > length || n > length) {
return false;
}
ListNode* pm = head;
ListNode* ppm = NULL;
ListNode* pn = head;
ListNode* ppn = pn->next;
for(int i=1; i<m; i++) {
ppm=pm;
pm=pm->next;
}
for(int i=1; i<n; i++) {
pn=pn->next;
ppn=pn->next;
}
ListNode* storem = pm;
ListNode* pNext = pm->next;
while(pNext<pn) {
ListNode* temp = pNext->next;
pNext->next = pm;
pm = pNext;
pNext = temp;
}
pn->next = pm;
if (ppm == NULL && ppn == NULL) {
storem->next = NULL;
return pn;
}
storem->next = ppn;
if (ppm == NULL) {
return pn;
}
ppm->next = pn;
return head;
}
int main() {
ListNode* head = new ListNode(-1);
ListNode* next = new ListNode(-3);
ListNode* nnext = new ListNode(-4);
head->next = next;
head->next->next = nnext;
ListNode* temp = reverseBetween(head, 2,3);
while(temp) {
std::cout << temp->val << " ";
temp = temp->next;
}
std::cout << std::endl;
return 0;
}
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *reverseBetween(ListNode *head, int m, int n) {
if (m >= n || head==NULL) {
return head;
}
int length =0;
ListNode* pHead = head;
while(pHead) {
length++;
pHead=pHead->next;
}
if (m > length || n > length) {
return false;
}
ListNode* pm = head;
ListNode* ppm = NULL;
ListNode* pn = head;
ListNode* ppn = pn->next;
for(int i=1; i<m; i++) {
ppm=pm;
pm=pm->next;
}
for(int i=1; i<n; i++) {
pn=pn->next;
ppn=pn->next;
}
ListNode* storem = pm;
ListNode* pNext = pm->next;
while(pNext<pn) {
ListNode* temp = pNext->next;
pNext->next = pm;
pm = pNext;
pNext = temp;
}
pn->next = pm;
if (ppm == NULL && ppn == NULL) {
storem->next = NULL;
return pn;
}
storem->next = ppn;
if (ppm == NULL) {
return pn;
}
ppm->next = pn;
return head;
}
int main() {
ListNode* head = new ListNode(-1);
ListNode* next = new ListNode(-3);
ListNode* nnext = new ListNode(-4);
head->next = next;
head->next->next = nnext;
ListNode* temp = reverseBetween(head, 2,3);
while(temp) {
std::cout << temp->val << " ";
temp = temp->next;
}
std::cout << std::endl;
return 0;
}