c语言中栈是一种数据结构,后进先出,即最后进入栈的数据最先弹出。c语言中没有栈这种数据类型,需要自己编程构建。下面我们就一起来了解一下c语言中栈的基本操作。
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
131
132
133
134
135
136
137
138
139
|
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE, * PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK, * PSTACK; //PSTACK等价于struct STACK *
void init(PSTACK); //初始化栈
void push(PSTACK, int ); //压栈
void traverse(PSTACK); //遍历
bool pop(PSTACK pS, int * pVal); //出栈
void clear(PSTACK pS); //清空栈
int main( void )
{
STACK S; //STACK等价于struct Stack
int val;
init(&S); //造出空栈
push(&S, 1); //压栈
push(&S, 2);
push(&S, 3);
push(&S, 4);
push(&S, 5);
push(&S, 6);
traverse(&S); //遍历输出
/*
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是%d\n", val);
}
else
{
printf("出栈失败!\n");
}
*/
clear(&S);
traverse(&S);
return 0;
}
void init(PSTACK pS)
{
pS->pTop = (PNODE) malloc ( sizeof (NODE));
if (NULL == pS->pTop)
{
printf ( "动态内存分配失败\n" );
exit (-1);
}
else
{
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL;
}
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE) malloc ( sizeof (NODE)); //创建新的节点
pNew->data = val; //将val的值赋给新节点的数据域
pNew->pNext = pS->pTop; //将新节点的指针域指向下一个节点.pS->Top不能改写成pS->Bottom
pS->pTop = pNew; //pTop指向新节点
return ;
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while (p != pS->pBottom)
{
printf ( "%d " , p->data);
p = p->pNext;
}
printf ( "\n" );
return ;
}
bool empty(PSTACK pS)
{
if (pS->pTop == pS->pBottom)
{
return true ;
}
else
{
return false ;
}
}
bool pop(PSTACK pS, int * pVal)
{
if (empty(pS))
{
return false ;
}
else
{
PNODE r = pS->pTop;
*pVal = r->data;
pS->pTop = r->pNext;
free (r);
r = NULL;
return true ;
}
}
//清空栈
void clear(PSTACK pS)
{
if (empty(pS)) //如果
{
return ;
}
else
{
PNODE p = pS->pTop; //定义元素p指向栈顶元素
PNODE q = NULL; //定义元素q,初始值为空
while (p !=pS->pBottom) //如果栈不为空
{
q = p->pNext; //q指向p的下一个元素
free (p); //释放p所指向的栈顶元素
p = q; //将q所指向的元素赋给p
}
pS->pTop = pS->pBottom;
}
}
|
希望本文所述对大家c程序设计有所帮助。