#include<stdio.h>
#include<stdlib.h>
typedef struct student{
int data;
struct student *pnext;
}node,*nodes;
typedef struct Stack{
nodes top;//栈顶
nodes bottom;//栈底
}*stacks,st;
void init(stacks S)//初始化栈
{
S->top=(stacks)malloc(sizeof(st));
if(NULL==S->top)
{
printf("内存分配失败!\n");
exit(0);
}
S->bottom=S->top;
S->bottom->pnext=NULL;
}
void push(stacks S,int n)//压栈
{
nodes pnew;
pnew=(nodes)malloc(sizeof(node));
pnew->data=n;
pnew->pnext=S->top;
S->top=pnew;
}
void trvel(stacks S)//遍历栈
{
nodes p;
p=S->top;
while(p!=S->bottom)
{
printf("%d ",p->data);
p=p->pnext;
}
}
bool Empty(stacks S)//判断是否为空栈
{
if(S->bottom==S->top)
return false;
else
return true;
}
bool Delete(stacks S)//删除栈顶元素
{
if(Empty(S)==false)
{
printf("空栈\n");
exit(0);
}
nodes r;
r=S->top;
S->top=r->pnext;
free(r);
r=NULL;
return true;
}
int main()
{
struct Stack S;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
trvel(&S);
Delete(&S);
trvel(&S);
}
C语言 栈的创建、插入、删除、遍历
最新推荐文章于 2023-11-24 22:47:50 发布