-
Notifications
You must be signed in to change notification settings - Fork 6
/
16_ReverseList.cpp
117 lines (100 loc) · 1.56 KB
/
16_ReverseList.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
113
114
115
116
117
#include <iostream>
using namespace std;
struct Node
{
int value;
Node *next;
};
void CreateList(Node **root, int n)
{
int i, tmp;
Node *index;
if (n <= 0)
return ;
*root = new Node;
cin >> (*root)->value;
(*root)->next = NULL;
index = *root;
for (i = 1; i < n; i ++)
{
cin >> tmp;
index->next = new Node;
index = index->next;
index->value = tmp;
index->next = NULL;
}
return ;
}
void DeleteList(Node **root)
{
Node *index, *tmp;
index = *root;
if (index == NULL)
return ;
while (index == NULL)
{
tmp = index;
index = index->next;
delete tmp;
}
return ;
}
Node* ReverseList(Node *pHead)
{
Node *pReversedHead = NULL;
Node *pNode = pHead;
Node *pPrev = NULL;
while(pNode != NULL)
{
pHead = pNode->next;
if(pHead == NULL)
pReversedHead = pNode;
pNode->next = pPrev;
pPrev = pNode;
pNode = pHead;
}
return pReversedHead;
}
Node *head = NULL;
Node * RecursionList(Node *node)
{
Node *index;
if (node == NULL)
return NULL;
if (node->next == NULL)
{
head = node;
return node;
}
index = RecursionList(node->next);
index->next = node;
node->next = NULL;
return node;
}
int main(void)
{
int n, i;
Node *root = NULL, *index, *ListHead;
while (cin >> n)
{
if (n <= 0)
{
cout << "NULL" << endl;
continue;
}
CreateList(&root, n);
ListHead = ReverseList(root);
// ListHead = RecursionList(root);
index = ListHead;
for (i = 0; i < n; i++)
{
cout << index->value;
if (i != n - 1)
cout << " ";
index = index->next;
}
cout << endl;
DeleteList(&ListHead);
}
return 0;
}