#include
#include
#include
typedef struct stack
{
int data;
struct stack *next;
}stack;
stack *InitStack(stack *top); //初始化堆栈
void display(stack *top); // 展示堆栈中的内容
stack *push(stack *top,int num);
stack *pop(stack *top);
int main()
{
stack *top=NULL;
top=InitStack(top);
top=push(top,10);
display(top);
printf("\n");
top=push(top,20);
display(top);
printf("\n");
pop(top);
display(top);
printf("\n");
pop(top);
display(top);
}
stack *InitStack(stack *top)
{
top=(stack *)malloc(sizeof(stack));
top->next=NULL;
return top;
}
void display(stack *top)
{
if(top->next==NULL)
{
printf("EMPTY");
exit(0);
}
stack *p=top;
while(p->next) //top表示头节点,数据存储在top->next
{
p=p->next;
printf("%d \n",p->data);
}
}
stack *push(stack *top,int num)
{
stack *p;
p=(stack *)malloc(sizeof(stack));
p->data=num;
p->next=top->next;
top->next=p;
return top;
}
stack *pop(stack *top)
{
if(top->next==NULL)
{
printf("EMPTY");
exit(0);
}
stack *p=top->next;
top->next=top->next->next;
free(p);
return top;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)