-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.cpp
105 lines (94 loc) · 1.41 KB
/
Stack.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
#include <iostream>
using namespace std;
struct Node
{
int info;
struct Node *pNext;
};
typedef struct Node NODE;
struct Stack
{
NODE *pHead;
};
typedef struct Stack STACK;
void CreateStack(STACK &s)
{
s.pHead = NULL;
}
NODE *CreateNode(int x)
{
NODE *p = new NODE;
if (p == NULL)
return NULL;
p->info = x;
p->pNext = NULL;
return p;
}
int IsEmpty(STACK s)
{
if (s.pHead == NULL)
return 1;
return 0;
}
void Push(STACK &s, NODE *p)
{
if (IsEmpty(s) == true)
s.pHead = p;
else
{
p->pNext = s.pHead;
s.pHead = p;
}
}
int Pop(STACK &s)
{
if (IsEmpty(s) == true)
return 0;
NODE *p = s.pHead;
int x = p->info;
s.pHead = s.pHead->pNext;
delete p;
return x;
}
int Top(STACK s)
{
if (IsEmpty(s) == true)
return 0;
return s.pHead->info;
}
int Size(STACK s)
{
int count = 0;
NODE *p = s.pHead;
while (p != NULL)
{
count++;
p = p->pNext;
}
return count;
}
void PrintStack(STACK s)
{
while (IsEmpty(s) == false)
{
int x;
cout << Pop(s) << " ";
}
}
int main()
{
STACK s;
CreateStack(s);
NODE *p = CreateNode(1);
Push(s, p);
p = CreateNode(2);
Push(s, p);
p = CreateNode(3);
Push(s, p);
p = CreateNode(4);
Push(s, p);
p = CreateNode(5);
Push(s, p);
PrintStack(s);
return 0;
}