数组实现堆栈

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

  定义头文件:

 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 }

 

posted @ 2016-10-23 23:20  dtdyq  阅读(725)  评论(0编辑  收藏  举报