数组实现堆栈

  堆栈是一种重要的数据结构,有不同的实现方式,该程序示范了如何用数组实现简单的栈操作。

  定义头文件:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define MAX_SIZE 10
 4 int stack[MAX_SIZE];
 5 int top=-1; 
 6 
 7 void push(int element);
 8 int pop();
 9 int isEmpty();
10 int isFull();
11 void stackFull();
12 void stackEmpty(); 
13 void print(int stack[]);

入栈操作:

1 void push(int element){
2     if(isFull()){
3         stackFull(); 
4     } 
5     stack[++top]=element; 
6 }

出栈操作:

1 int pop(){
2     if(isEmpty()){
3         stackEmpty(); 
4     }
5     return stack[top--]; 
6 } 

判断是否栈满:

1 int isFull(){
2     if(top==MAX_SIZE-1)
3         return 1;
4     return 0; 
5 }

判断是否为空栈:

1 int isEmpty(){
2     if(top<0)
3         return 1;
4     return 0;
5 } 

一下分别是栈满和栈空时的操作:

1 void stackFull(){
2     fprintf(stderr,"stack is full,cannot push more!"); 
3     exit(EXIT_FAILURE); 
4 } 
5 void stackEmpty(){
6     fprintf(stderr,"stack is empty,cannot pop more!"); 
7     exit(EXIT_FAILURE); 
8 }

打印所有的栈元素(打印后所有栈中的元素也将不存在!):

1 void print(int stack[]){
2     while(!isEmpty()){
3         printf("%4d",pop());
4     } 
5 } 

主函数测试:

 1 int main(void)
 2 {
 3     int i;
 4     for(i=0;i<10;i++){ 
 5         push(i+1);
 6     }
 7     pop();
 8     pop(); 
 9     print(stack); 
10     pop(); 
11     return 0;    
12 }

 

转载于:https://www.cnblogs.com/dtdyq/p/5991443.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值