首页 > 代码库 > 算法7---栈及其基本操作实现

算法7---栈及其基本操作实现

有关栈的基本概念随便找一本书上面都有详细的介绍,在这里我用c语言只实现。

这一部分包括一些基本的栈的操作,初始化,出栈,入栈,判空,判满,清空等操作。

  1 #include <Stdlib.h>  2 #include <stdio.h>  3 #include <string.h>  4   5 #define MAXLEN 50  6   7 typedef struct  8 {  9     int age; 10     char name[10]; 11 }DATA; 12  13 typedef struct stack 14 { 15     DATA data[MAXLEN]; 16     int top;    17 }stackType; 18  19 stackType *inistack() 20 { 21     stackType *p; 22     if (p=(stackType *)malloc(sizeof(stackType ))) 23     { 24         p->top=0; 25         return p; 26     } 27     return NULL; 28 } 29  30 int stackEmpty(stackType *s) 31 { 32     int flag; 33     flag=(s->top==0); 34     return flag; 35 } 36  37 int stackFull(stackType *s) 38 { 39     int flag; 40     flag=(s->top==MAXLEN); 41     return flag; 42 } 43  44 void clearStack(stackType *s) 45 { 46     s->top=0; 47 } 48  49 void freeStack(stackType *s) 50 { 51     if (s) 52     { 53         free(s); 54     } 55 } 56  57 int pushStack(stackType *s,DATA data) 58 { 59     if ((s->top+1)>MAXLEN) 60     { 61         printf("overflow!\n"); 62         return 0; 63     } 64     s->data[++s->top]=data; 65     return 1; 66 } 67  68 DATA popStack(stackType *s) 69 { 70     if (s->top==0) 71     { 72         printf("empty stack!\n"); 73         exit(0); 74     } 75     return (s->data[s->top--]); 76 } 77  78  79 DATA readStack(stackType *s) 80 { 81     if (s->top==0) 82     { 83         printf("the stack is empty!\n"); 84         exit(0); 85     } 86     return (s->data[s->top]); 87 } 88  89 int main() 90 { 91     stackType *stack; 92     DATA data,data1; 93     stack=inistack(); 94     printf("push stack!\n"); 95     printf("input name,age to push data!\n"); 96     do 97     { 98         scanf("%s%d",data.name,&data.age); 99         if (strcmp(data.name,"0")==0)100         {101             break;102         }103         else104         {105             pushStack(stack,data);106         }107     }while(1);108 109     do110     {111         printf("pop stack operation!\n");112         data1=popStack(stack);113         printf("the pop stack data is (%s,%d)\n",data1.name,data1.age);114     }while(1);115 116 117     freeStack(stack);118     return 0;119 120 }

 

算法7---栈及其基本操作实现