(c语言简单链栈代码!!)
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct node//链栈的结构体
{
elemtype data;//自定义元素
struct node *next;//和结构体一样格式的指针
}linkstack;//自命名
linkstack *top;//定义栈顶
void setnull()//置空栈
{
top = NULL;
}
int isempty()//判断栈空
{
if(top == NULL)
return 1;
else
return 0;
}
void push(elemtype x)//压栈,因为链栈没有顶不考虑溢出问题
{
linkstack *p;
p = (linkstack *)malloc(sizeof(linkstack));
p->data = x;
p->next = top;
top = p;
}
void pop()//出栈
{
if(top == NULL)//如果栈为空,输出
puts("栈为空");
else
{
linkstack *p;
p = top;//因为后面要盖面top的值,所以先设置一个同样类型的指针p来定位top的值
printf("%d\n",top->data);
top = top->next;//降栈顶
free(p);//释放p空间
}
}
int main()
{
int k;
setnull();
k = isempty();
push(1);
push(2);
pop();
pop();
pop();//栈空
return 0;
}
``