//创建堆栈,压栈,出栈,遍历栈,清空栈 2012.7.20
#include
#include
#include
void init_stack(struct stack *ps);//初始化
void push(struct stack *ps); //压栈
void pop(struct stack *ps); //出栈
void clear_stack(struct stack *ps);//清空栈
void output_stack(struct stack *ps);// 显示栈的内容
int is_empty(struct stack *ps); //判断是否为空栈
//结构体
struct node
{
char no[20];
char name[20];
struct node * pnext;
};
//结构体
struct stack
{
struct node * top;
struct node * bottom;
};
//主函数
int main(void)
{
int i;
struct stack s;
printf("开始初始化..........\n");
init_stack(&s);
printf("初始化成功!\n");
printf("开始压栈!\n");
for(i=0;i<2;i++)
{
push(&s);
}
printf("压栈完成!\n");
printf("显示栈!\n");
output_stack(&s);
printf("开始出栈!\n");
pop(&s);
printf("显示栈!\n");
output_stack(&s);
printf("清空栈!\n");
clear_stack(&s);
printf("显示栈!\n");
output_stack(&s);
return 0;
}
//初始化,建立一个空的栈
void init_stack(struct stack *ps)
{
ps->top = (struct node *)malloc(sizeof(struct node));
if(ps->top == NULL)
{
printf("内存分配失败!\n");
exit(-1);
}
else
{ ps->bottom = ps->top;
(ps->top)->pnext = NULL;
}
return ;
}
//压栈,链表原理
void push(struct stack *ps)
{
struct node *p;
p = (struct node *)malloc(sizeof(struct node));
if(p == NULL)
{
printf("内存分配失败!\n");
exit(-1);
}
else
{printf("请压入学号:");
scanf("%s",p->no);
printf("请压入姓名:");
scanf("%s",p->name);
p->pnext = ps->top;
ps->top = p;
printf(" 压入成功!\n");
}
return;
}
//出栈 链表原理
void pop(struct stack *ps)
{
struct node * p;
if(is_empty(ps))
{ printf("栈是空的,没数据可出!\n");
return;
}
else
{
p = ps->top;
ps->top = p->pnext;
free(p);
}
return;
}
//清空栈里的内容
void clear_stack(struct stack *ps)
{
struct node * p,*q;
if(is_empty(ps))
{printf("栈是空的,不能再清除!\n");
return ;
}
else
{ p = ps->top; // 定义两个指针变量,同时指向栈顶
q = p