-
Notifications
You must be signed in to change notification settings - Fork 6
/
05_ListOperators.cpp
116 lines (96 loc) · 1.93 KB
/
05_ListOperators.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
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int value;
ListNode *next;
};
ListNode *create_list(ListNode **root)
{
ListNode *tmp = NULL, *head = NULL;
int value;
cin >> value;
if (value == -1)
return 0;
head = new(ListNode);
if (head == NULL) return 0;
head->value = value;
tmp = head;
cin >> value;
while (value != -1)
{
tmp->next = new(ListNode);
tmp = tmp->next;
tmp->value = value;
cin >> value;
}
tmp->next = NULL;
*root = head;
return head;
}
void InsertNode(ListNode **pHead, int value) {
ListNode *pNew = new ListNode();
pNew->next = NULL;
pNew->value = value;
if(*pHead==NULL || (*pHead)->value > value) {
pNew->next = (*pHead)->next;
*pHead = pNew;
}
else {
ListNode *pNode = *pHead;
while(pNode->next != NULL && pNode->next->value <= value) {
pNode = pNode->next;
}
if(pNode->next == NULL) {
pNode->next = pNew;
}
else {
pNew->next = pNode->next;
pNode->next = pNew;
}
}
}
void PrintListReversingly_Iteratively(ListNode *pHead) {
stack<ListNode *> nodes;
ListNode *pNode = pHead;
while(pNode != NULL)
{
nodes.push(pNode);
pNode = pNode->next;
}
while(!nodes.empty())
{
pNode = nodes.top();
cout << pNode->value << endl;
nodes.pop();
}
}
void Print_TailtoHead(ListNode *pHead) {
ListNode *pNode = pHead;
if(pNode != NULL) {
Print_TailtoHead(pNode->next);
cout<<pNode->value<<endl;
}
}
void destroy(ListNode *pHead) {
ListNode *tmp = NULL;
while(pHead != NULL)
{
tmp = pHead->next;
delete pHead;
pHead = tmp;
}
}
int main(void)
{
ListNode *root = NULL;
create_list(&root); //input 1, 2, 5, -1
InsertNode(&root, 0);
InsertNode(&root, 4);
InsertNode(&root, 6);
PrintListReversingly_Iteratively(root);
Print_TailtoHead(root);
destroy(root);
return 0;
}