将链表的一部分(from~to)反转。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class node
{
public:
node(int x):val(x), next(NULL){}
~node();
int val;
node* next;
};
void printList(node* head){
node* p = head;
while(p){
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
int reverseList(node* &head, int from, int to){
if(!head || head->next == NULL || from >= to){
return 0;
}
node* p = head;
int len = 0;
while(p){
len++;
p = p->next;
}
if(to > len || from <= 0)
return 0;
node* h = new node(0);
h->next = head;
node* h1 = h; // h1指向from的上一个
for(int i = 0; i < from - 1; ++i){
h1 = h1->next;
}
node* t1 = h; // t1指向to的下一个
for(int i = 0; i < to + 1; i++){
t1 = t1->next;
}
node* p1 &#