顺序栈
顺序栈的实现
顺序栈是利用顺序存储结构实现的栈,即利用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素,同时附设指针top指示栈顶元素在顺序栈中的位置。
1 #include "stdio.h" 2 #include "stdlib.h" 3 4 #define OK 1 5 #define ERROR 0 6 #define OVERFLOW -1 7 #define MAX_STACK_SIZE 100 8 9 #define true 1 10 #define false 0 11 12 typedef int SElemType; 13 typedef struct Stack{ 14 SElemType *base; /*栈底指针*/ 15 SElemType *top; /*栈顶指针*/ 16 int stacksize; /*栈可用的最大容量*/ 17 }SeqStack; 18 19 /*顺序栈的初始化*/ 20 int InitStack(SeqStack *S){ 21 /*为顺序栈动态分配一个最大容量为MAX_STACK_SIZE的数组空间*/ 22 S->base = (int*)malloc(MAX_STACK_SIZE*sizeof(int)); 23 if(!S->base) exit(OVERFLOW); /*分配失败*/ 24 S->top = S->base; /*top起始为base,空栈*/ 25 S->stacksize = MAX_STACK_SIZE; /*初始栈的容量为MAX_STACK_SIZE*/ 26 return OK; 27 } 28 29 /*入栈*/ 30 int PushElem(SeqStack *S, SElemType e){ 31 if(S->top - S->base == S->stacksize) 32 return ERROR; /*栈满*/ 33 *S->top++ = e; /*将元素e压入栈顶,栈顶指针加1*/ 34 return OK; 35 } 36 37 /*出栈*/ 38 int PopElem(SeqStack *S, SElemType *e){ 39 if(S->top == S->base) return ERROR; /*栈空*/ 40 *e = *--S->top; /*将栈顶元素赋值给e,栈顶指针减1*/ 41 return OK; 42 } 43 44 /*取栈顶元素*/ 45 int GetTop(SeqStack S, SElemType *e){ 46 if(S.base == S.top) return ERROR; 47 *e = *(S.top-1); 48 return OK; 49 } 50 51 /*栈长*/ 52 int StackLength(SeqStack S){ 53 return S.top-S.base; 54 } 55 56 /*遍历栈*/ 57 int Traverse(SeqStack S){ 58 if(S.base == S.top) return ERROR; 59 int *p, *q; 60 p = S.base; 61 q = S.top; 62 printf("栈底到栈顶的元素依次为:"); 63 while(p != q) printf("%d ", *p++); 64 printf("\n"); 65 return OK; 66 } 67 68 /*清空栈*/ 69 void ClearStack(SeqStack *S){ 70 S->top = S->base; 71 } 72 73 void main() 74 { 75 SeqStack S; 76 int e, select; 77 InitStack(&S); 78 while(true) 79 { 80 //printf("\t---请根据功能选择编号---"); 81 printf("\n\t1.入栈"); 82 printf("\n\t2.出栈"); 83 printf("\n\t3.取顶"); 84 printf("\n\t4.栈长"); 85 printf("\n\t5.遍历"); 86 printf("\n\t6.清空"); 87 printf("\n 请输入功能编号:"); 88 scanf("%d", &select); 89 printf("\n"); 90 switch(select) 91 { 92 case 1: 93 printf("请输入入栈元素:\n"); 94 scanf("%d", &e); 95 if(PushElem(&S, e)) printf("入栈成功!\n"); 96 else printf("入栈失败!栈已满\n"); 97 break; 98 case 2: 99 if(PopElem(&S, &e)) printf("出栈成功!出栈元素为:%d\n", e); 100 else printf("出栈失败!栈为空栈!\n"); 101 break; 102 case 3: 103 if(GetTop(S, &e)) printf("栈顶元素为:%d\n", e); 104 else printf("栈为空栈!\n"); 105 break; 106 case 4: 107 printf("栈的当前长度为:%d\n栈的最大长度为:%d\n", StackLength(S), S.stacksize); 108 break; 109 case 5: 110 if(!Traverse(S)) printf("栈为空栈!\n"); 111 break; 112 case 6: 113 ClearStack(&S); 114 printf("栈已清空!\n"); 115 break; 116 default: 117 printf("输入有误,请重新输入\n"); 118 break; 119 }/*endswitch*/ 120 }/*endwhile*/ 121 }/*endmain*/

浙公网安备 33010602011771号