-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
130 lines (110 loc) · 1.97 KB
/
stack.c
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
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<stdio.h>
#include<stdlib.h>
#ifndef _Stack_h
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode Stack;
typedef int ElementType;
int IsEmpty(Stack S);
Stack CreateStack(void);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X,Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
#endif //_Stack_h
//Place in implementation file
//Stack implementation is a linked list with a header
struct Node
{
ElementType Element;
PtrToNode Next;
};
int main()
{
Stack S = CreateStack();
printf("is stack empty? %d\n",IsEmpty(S));
int i;
for(i = 0;i < 6;i++)
Push(i,S);
printf("Now on the top of the element is: %d\n",Top(S));
Pop(S);
Pop(S);
printf("Now on the top of the element is: %d\n",Top(S));
return 0;
}
int IsEmpty(Stack S)
{
return S->Next == NULL;
}
Stack CreateStack(void)
{
Stack NewStack = malloc(sizeof(struct Node));
if(NewStack == NULL)
{
printf("malloc error!");
exit(0);
}
//NewStack->Element = 0;
NewStack->Next = NULL;
MakeEmpty(NewStack);
return NewStack;
}
void MakeEmpty(Stack S)
{
if(S == NULL)
{
printf("must use createstack first!");
exit(0);
}
else
{
while(!IsEmpty(S))
Pop(S);
}
}
void Push(ElementType X,Stack S)
{
PtrToNode TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL)
{
printf("malloc error!");
exit(0);
}
else
{
TmpCell->Element = X;
TmpCell->Next = S->Next;
S->Next = TmpCell; //S在未push之前为栈顶元素
}
}
ElementType Top(Stack S)
{
if(!IsEmpty(S))
return S->Next->Element;
printf("error stack");
return 0; //return value used to avoid warning
}
void Pop(Stack S)
{
PtrToNode FirstCell;
if(IsEmpty(S))
{
printf("Empty Stack!");
exit(0);
}
else
{
FirstCell = S->Next;
S->Next = S->Next->Next;
free(FirstCell);
}
}
void DisposeStack(Stack S)
{
if(!IsEmpty(S))
{
free(S);
}
}