深度解析栈操作

来源:互联网 发布:知乎miya的米牙 编辑:程序博客网 时间:2024/06/10 04:38

此篇为原创,如需转载,请注明出处:http://blog.csdn.NET/qq_36759732

栈是一种特殊的表,这种表只在表头进行插入和删除操作。因此,表头对于栈来说具有特殊的意义,称为栈顶。相应地,表尾称为栈底。不含任何元素的栈称为空栈。栈的特点:后进先出。 

通过此篇,你将会深入了解到栈的基本操作,便于以后使用栈时更加清楚。大家知道,对于栈的操作,有出栈,入栈,查看栈顶元素等,但它本质上是如何实现的呢,下面我会通过代码实现栈的基本操作。

栈中可以存放各种类型,甚至可以再存放一个栈,为了便于解释,下面操作用存放整型数据元素实现。编程环境:Linux

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3
  4 #define OK 1
  5 #define ERROR 0
  6
  7 typedef struct stack{
  8     int *data;
  9     int top;
 10     int length;
 11 }*Stack;
 12
 13 void init(Stack s, int n = 100){ //初始化
 14     s->data = (int *)malloc(n * sizeof(int));
 15     s->top = -1;
 16     s->length = n;
 17 }
 18
 19 int empty(Stack s){ //判空

 20     return s->top == -1;
 21 }
 22
 23 int push_stack(Stack s, int value){ // 入栈
 24     if(s->top == s->length - 1) return ERROR;
 25     ++s->top;
 26     s->data[s->top] = value;
 27     return OK;
 28 }
 29
 30 int pop_stack(Stack s){ // 出栈
 31     if(empty(s))  return ERROR;
 32     printf("出栈: %d\n", s->data[s->top]);
 33     --s->top;
 34     return OK;
 35 }
 36
 37 void seek(Stack s){ // 查看栈顶元素
 38     if(empty(s))  return ;
 39     printf("栈顶元素top:%d\n", s->data[s->top]);
 40 }
 41
 42 void output(Stack s){ // 输出栈
 43     printf("STACK:\n");
 44     if(empty(s)) return ;
 45     for(int i = s->top ; i >= 0; --i){
 46         printf("%5d\n",s->data[i]);
 47         printf("|___________|\n");
 48     }
 49     return ;
 50 }
 51
 52 void clear(Stack s){ // 清空
 53     free(s->data);
 54     free(s);
 55 }
 56
 57 int main(){
 58     printf("/***********************************/\n");
 59     printf("0代表入栈,1代表出栈,2代表查看栈顶元素\n");
 60     printf("/***********************************/\n");
 61     Stack s = (Stack)malloc(sizeof(stack));
 62     init(s);
 63     int opr;
 64     int value;
 65     while(scanf("%d", &opr) != EOF){
 66         switch(opr){
 67             case 0:
 68                 printf("输入入栈元素:");
 69                 scanf("%d", &value);
 70                 push_stack(s, value);
 71                 output(s);
 72                 break;
 73             case 1:
 74                 pop_stack(s);
 75                 output(s);
 76                 break;
 77             case 2:
 78                 seek(s);
 79                 break;
 80         }
 81     }
 82     clear(s);
 83     return 0;
 84 }


以上是本人对栈操作的理解,欢迎大家指点与修正。后面我会上传关于链表的基本操作,大家敬请期待。