c语言创建堆栈,压栈,出栈,遍历栈,清空栈.doc
//创建堆栈,压栈,出栈,遍历栈,清空栈 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 ;
}
//压栈,链
表
关于同志近三年现实表现材料材料类招标技术评分表图表与交易pdf视力表打印pdf用图表说话 pdf
原理
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;
while(q->pnext != NULL)
{
q = p->pnext; //指向栈顶下一个节点
free(p); //删除栈顶
p = q; //同时指向新栈顶
}
ps->top = p; //指向栈顶
}
return ;
}
//判断堆栈是否为空
int is_empty(struct stack *ps) {
if(ps->top == ps->bottom)
return 1;
else
return 0;
}
//显示栈里的内容
void output_stack(struct stack *ps)
{
struct node * p;
if(is_empty(ps))
{printf("栈是空的,无数据可显示~\n");
return;
}
else
{ p = ps->top;
while(p->pnext != NULL)
{
printf("学号:%s 姓名:%s\n",p->no,p->name);
p = p->pnext;
}
}
return;
}