-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest24.cpp
112 lines (89 loc) · 1.26 KB
/
test24.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include<iostream>
#include<string>
#include<vector>
using namespace std;
typedef struct node
{
int key;
struct node *next;
}Node;
Node *ReverseList(Node *head)
{
if(!head)
{
cerr<<"input is invalid"<<endl;
return nullptr;
}
Node *pre=nullptr;
Node *cur=head;
Node *next=nullptr;
while(cur)
{
next=cur->next;
if(!next) head=cur;
cur->next=pre;
pre=cur;
cur=next;
}
return head;
}
Node *ReverseCore(Node *pre,Node *cur)
{
if(!cur) return pre;
Node *next=cur->next;
cur->next=pre;
Node *head=ReverseCore(cur,next);
return head;
}
Node *ReverseListRecursion(Node *head)
{
if(!head)
{
cerr<<"input is invalid"<<endl;
return nullptr;
}
Node *pre=nullptr;
head=ReverseCore(pre,head);
return head;
}
void print(Node *head)
{
if(!head)
{
cerr<<"input is invalid"<<endl;
return;
}
Node *tmp=head;
while(tmp)
{
cout<<tmp->key<<" ";
tmp=tmp->next;
}
cout<<endl;
}
int main()
{
Node *head=nullptr;
Node *tmp=nullptr;
for(int i=0;i<1;++i)
{
Node *newnode=new Node;
newnode->key=i;
newnode->next=nullptr;
if(i==0)
{
head=newnode;
tmp=head;
}
else
{
tmp->next=newnode;
tmp=tmp->next;
}
}
print(head);
//head=ReverseList(head);
head=ReverseListRecursion(head);
print(head);
return 0;
}