堆栈程序

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>


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;


   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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值