-
Notifications
You must be signed in to change notification settings - Fork 1
/
两两翻转链表.cpp
66 lines (60 loc) · 1.07 KB
/
两两翻转链表.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
using namespace std;
class Node
{
public:
Node(int value) : _next(nullptr), _value(value) { }
~Node()
{
delete _next;
}
public:
int _value;
Node* _next;
};
Node* makeList()
{
int rootValue;
Node* head = new Node(-1);
Node* pRoot = head;
while (cin >> rootValue) {
if (rootValue == -1) break;
head->_next = new Node(rootValue);
head=head->_next;
//printf("%d\n",rootValue);
}
/*while(pRoot){
cout << pRoot->_value << endl;
pRoot=pRoot->_next;
}*/
return pRoot->_next;
}
Node* helper(Node* head)
{
if(!head) return head;
if(!head->_next) return head;
Node* one=head;
Node* two=head->_next;
Node* last=two->_next;
one->_next=helper(last);
two->_next=one;
return two;
}
int main()
{
Node* pRoot = makeList();
if(!pRoot) return 0;
if(!pRoot->_next) {
cout<< pRoot->_value<<endl;
return 0;
}
Node* ans=pRoot->_next;
helper(pRoot);
while(ans){
cout<<ans->_value<<endl;
ans=ans->_next;
}
delete pRoot;
return 0;
}