#include <iostream> #include <malloc.h> using namespace std; typedef struct linknode { int data; struct linknode *next; }Listack; //初始化栈 void init(Listack *&s) { s=(Listack*)malloc(sizeof(Listack)); s->next=NULL; } //摧毁栈 void destroy(Listack *&s) { Listack *p=s,*q=s->next; while(q!=NULL) { free(p); p=q; q=q->next; } free(p); } //判断栈是否为空 bool empty(Listack *s) { return s->next==NULL; } //进栈 void push(Listack *&s,int e) { Listack *q; q=(Listack*)malloc(sizeof(Listack)); q->next=s->next; q->data=e; s->next=q; } //出栈 void pop(Listack *&s) { if(s->next==NULL) { cout<<"栈为空,不能删除!"; return; } Listack *p; p=s->next; s->next=p->next; free(p); } //取栈顶元素 int top(Listack *&s) { if(s->next==NULL) { cout<<"栈为空,无元素!"; return 0; } Listack *p; p=s->next; return p->data; } int main() { Listack *s; init(s); push(s,2); push(s,4); cout<<top(s)<<endl; pop(s); cout<<top(s)<<endl; return 0; }