数据结构之栈的相关操作

  1 //栈的顺序存储相关操作
  2 #include<stdio.h>
  3 #include<stdlib.h>
  4 //#include<string.h>
  5 #define MAX 100
  6 //定义结构体
  7 typedef struct Stack
  8 {
  9     int *data;
 10     int *top;
 11     int stacksize;
 12 }Stack;
 13 //初始化空栈
 14 int stackinit(Stack *s)
 15 {
 16     s->data=(int*)malloc(sizeof(int)*MAX);
 17     if(s->data==NULL)
 18     {
 19         printf("初始化失败!");
 20     }
 21     s->top=s->data;
 22     s->stacksize=MAX;
 23     return 0;
 24 }
 25 
 26 //判断是否为空
 27 int stackisempty(Stack *s)
 28 {
 29     if(s->data==s->top)
 30     {
 31         return 1;
 32     }
 33     else
 34     {
 35         return 0;
 36     }
 37 }
 38 //进栈
 39 int stackpush(Stack *s,int a)
 40 {
 41     if(s->top-s->data>=s->stacksize)
 42     {
 43         s->data=(int*)realloc(s->data,sizeof(int)*(MAX+s->stacksize));
 44         if(s->data==NULL)
 45         {
 46             printf("重新分配空间失败!");
 47             return 0;
 48         }
 49         s->stacksize=s->stacksize+MAX;
 50         s->top=s->data+MAX;
 51     }
 52     *s->top=a;
 53     s->top++;
 54     return 1;
 55 }
 56 //出栈
 57 int stackpop(Stack *s,int *a)
 58 {
 59     if(stackisempty(s)==1)
 60     {
 61         printf("出栈失败!");
 62         return 0;
 63     }
 64     else
 65     {
 66         s->top--;
 67         *a=*s->top;
 68         return 1;
 69     }
 70 }
 71 
 72 //返回栈的长度
 73 int stacklength(Stack *s)
 74 {
 75     return (s->top-s->data);
 76 }
 77 //遍历栈
 78 int stacktraverse(Stack *s)
 79 {
 80     int *s1=NULL;
 81 //    s1=(int *)malloc(sizeof(int));
 82     s1=s->top;
 83     if(stackisempty(s)==1)
 84     {
 85         printf("栈为空!");
 86         return 0;
 87     }
 88     while(--s1!=s->data)
 89     {
 90         printf("%d  ",*s1);
 91     }
 92     printf("\n");
 93     return 1;
 94 }
 95 //清空栈
 96 int stackdestory(Stack *s)
 97 {
 98     s->top=s->data;
 99     return 1;
100 }
101 void main()
102 {
103     int i=0;
104     int a=0;
105     Stack s;
106     stackinit(&s);
107     for(i=0;i<10;i++)
108     {
109         stackpush(&s,i);
110     }
111     printf("length of s :%d\n",stacklength(&s));
112     stacktraverse(&s);
113     stackpop(&s,&a);
114     printf("pop:%d\n",a);
115     stacktraverse(&s);
116     printf("length of s :%d\n",stacklength(&s));
117     printf("s is empty?:%d\n",stackisempty(&s));
118     stackdestory(&s);
119     printf("s is empty?:%d\n",stackisempty(&s));
120 }

 

posted @ 2013-06-04 09:43  zxjay  阅读(710)  评论(0编辑  收藏  举报