// 假设你有一个链表, 输出两两翻转后的链表 // 1->2->3->4->5->6->7 // 2->1->4->3->6->5->7// 你必须定义一个 `main()` 函数入口。
#include <iostream>
using namespace std;
struct node {
int val;
node* next;
};
// 这是我的答案, 经过验证已经正确, 但是有一点内存泄漏.
node* reverse(node* root) {
// 1. add a super input
node* super_input = new node;
super_input->val = -1;
super_input->next = root;
// 2. init ptrs
node* cur = super_input;
while(cur->next && cur->next->next) {
node* tail = cur->next->next->next;
node* first =cur->next;
cur->next = cur->next->next;
cur->next->next = first;
first->next = tail;
cur = first;
}
return super_input->next;
}
//thanks
node* reverse_2(node* root) {
node* a = root;
node* b = root->next;
node* temp;
node* p = NULL;
node* n=b==NULL?a:b;
while(b!=NULL){
temp=b->next;
b->next=a;
a->next=temp;
if(p!=NULL){
p->next=b;
}
if(temp==NULL)
{
break;
}
p=a;
a=temp;
b=temp->next;
}
return n;
}
void print(node* root) {
while(root) {
cout << root->val << " ";
root = root->next;
}
cout << endl;
}
int main() {
node* root = new node;
root->val = 1;
root->next = new node;
root->next->val = 2;
root->next->next = new node;
root->next->next->val = 3;
root->next->next->next = new node;
root->next->next->next->val = 4;
root->next->next->next->next = new node;
root->next->next->next->next->val = 5;
root->next->next->next->next->next = NULL;
//node* ret = reverse(root);
node* ret = reverse_2(root);
print(ret);
return 0;
}