#include<iostream>
using namespace std;
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 (m == n)
return head;
ListNode* first = head;
ListNode* preFirst = head;
ListNode* last = head;
ListNode* cur = head;
while (--m > 0){
preFirst = first;
first = first->next;
}
while (n-- > 0)
last = last->next;//调整区域是前闭后开区间
if (first == preFirst){ //头结点就要调整
cur = first->next;
first->next = last;
while (cur != last){
ListNode* temp = cur;
cur = cur->next;
temp->next = head;
head = temp;
}
}else{ //头结点不需调整
preFirst->next = last;
cur = first->next;
ListNode* newHead = first;
while (cur != last){
ListNode* temp = cur;
cur = cur->next;
temp->next = newHead;
newHead = temp;
}
first->next = preFirst->next;
preFirst->next = newHead;
}
return head;
}
ListNode* createList(ListNode* head){
int numOfNode;
int value;
cout << "please input number of listNode:";
cin >> numOfNode;
cin >> value;
head = new ListNode(value);
ListNode* cur = head;
for (int i = 1; i < numOfNode; ++i){
cin >> value;
ListNode* temp = new ListNode(value);
cur->next = temp;
cur = temp;
}
return head;
}
void printNode(ListNode* head){
ListNode* cur = head;
while (cur){
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
};
int main(){
ListNode* head = NULL;
Solution solution;
head = solution.createList(head);
solution.printNode(head);
head = solution.reverseBetween(head, 1, 2);
solution.printNode(head);
system("pause");
return 0;
}