c语⾔push操作的作⽤,C语⾔对栈的实现基本操作
c语⾔中栈是⼀种数据结构,后进先出,即最后进⼊栈的数据最先弹出。c语⾔中没有栈这种数据类型,需要⾃⼰编程构建。下⾯我们就⼀起来了解⼀下c语⾔中栈的基本操作。
C语⾔对栈的实现基本操作,操作如下:
#include
#include
#include
#include
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 traver(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);
traver(&S); //遍历输出
/*
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是%d\n", val);
}
el
{
printf("出栈失败!\n");
}
*/
clear(&S);
traver(&S);
return 0;
学网球}
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if(NULL == pS->pTop)
{
printf("动态内存分配失败\n");
exit(-1);
月亮的秘密
}
el
{
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 traver(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;
}
el
{
return fal;
}
}
bool pop(PSTACK pS,int * pVal)
{
if(empty(pS))
{
return fal;
}
el
{
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;
}
能源问题el
{
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程序设计有所帮助。