-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChainStack.cpp
More file actions
113 lines (106 loc) · 1.72 KB
/
Copy pathChainStack.cpp
File metadata and controls
113 lines (106 loc) · 1.72 KB
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
#include <iostream>
using namespace std;
typedef struct Stack
{
int data;
struct Stack *next;
} StackElem, *ChainStack;
// 我们选用不带头结点的
void Init(ChainStack &S)
{
// 只有头指针
S = NULL;
cout << "Init……" << endl;
}
bool StackEmpty(ChainStack S)
{
if (S == NULL)
{
cout << "Empty" << endl;
return true;
}
return false;
}
bool push(ChainStack &S, int e)
{
StackElem *p;
p = (StackElem *)malloc(sizeof(StackElem));
p->data = e;
p->next = S;
S = p;
cout << "push:" << p->data << endl;
return true;
}
bool pop(ChainStack &S, int &pop)
{
if (StackEmpty(S))
{
return false;
}
StackElem *p = S;
pop = S->data;
S = S->next;
free(p);
return true;
}
void destroy(ChainStack &S)
{
StackElem *p = S;
StackElem *q;
while (p != NULL)
{
q = p;
p->data = 0;
p = p->next;
free(q);
q = NULL;
}
cout << "Destroy……" << endl;
}
bool GetTop(ChainStack S, int &pop)
{
if (StackEmpty(S))
{
return false;
}
pop = S->data;
return true;
}
void Print(ChainStack S)
{
StackElem *p = S;
cout << "List:";
while (p != NULL)
{
if (p->next == NULL)
{
cout << p->data;
p = p->next;
break;
}
cout << p->data;
cout << "->";
p = p->next;
}
cout << "\n";
}
int main()
{
ChainStack S;
Init(S);
StackEmpty(S);
int e = 0;
for (e = 0; e < 10; e++)
{
push(S, e);
}
Print(S);
int top;
GetTop(S, top);
for (e = 0; e < 10; e++)
{
pop(S, top);
Print(S);
}
destroy(S);
}