数据结构 --- 顺序栈(栈的顺序存储结构)
工程目录结构:
common.h:
1 //#ifndef __common_h__ 2 //#define __common_h__ 3 4 #define OK 1 5 #define ERROR 0 6 #define TRUE 1 7 #define FALSE 0 8 9 #define MAXSIZE 20 10 11 typedef int Status; //函数的返回结果,OK、ERREO、TRUE、FALSE 12 typedef int ElemType; //结点数据域的数据类型 13 14 //#endif
common.c:
1 #include "common.h" 2 3 Status visit(ElemType e) 4 { 5 printf("%d , ", e); 6 return OK; 7 }
Stack.h:
1 //顺序栈结构 2 typedef struct 3 { 4 ElemType data[MAXSIZE]; 5 int top; //栈顶指针 6 }SqStack;
Stack.c:
1 #include<stdio.h> 2 3 //注意以下两个 .h 的包含顺序 4 #include "common.h" 5 #include "Stack.h" 6 7 //创建空栈 8 Status InitStack(SqStack *S) 9 { 10 S->top = -1; 11 return OK; 12 } 13 14 //栈置为空 15 Status ClearStack(SqStack *S) 16 { 17 S->top = -1; 18 return OK; 19 } 20 21 Status StackEmpty(SqStack S) 22 { 23 if (1 == S.top) 24 return TRUE; 25 else 26 return FALSE; 27 } 28 29 int StackLength(SqStack S) 30 { 31 return S.top + 1; 32 } 33 34 //获取栈顶元素,不不删除 35 Status GetTop(SqStack S, ElemType *e) 36 { 37 if (S.top == -1) 38 { 39 return ERROR; 40 } 41 else 42 { 43 *e = S.data[S.top]; 44 } 45 return OK; 46 } 47 48 Status Push(SqStack *S, ElemType e) 49 { 50 //栈满 51 if (S->top >= MAXSIZE - 1) 52 { 53 return ERROR; 54 } 55 ++S->top; 56 S->data[S->top] = e; 57 return OK; 58 } 59 60 //获取栈顶元素,并删除 61 Status Pop(SqStack *S, ElemType *e) 62 { 63 if (S->top <= -1) 64 return ERROR; 65 66 *e = S->data[S->top]; 67 --S->top; 68 return OK; 69 } 70 71 //从栈底到栈顶依次对栈中每个元素显示 72 Status StackTraverse(SqStack S) 73 { 74 int index = 0; 75 while (index <= S.top) 76 { 77 visit(S.data[index++]); 78 } 79 return OK; 80 } 81 82 void StackStart() 83 { 84 printf("\n\n###### 栈 测试是 Start ###########\n"); 85 86 int j; 87 SqStack s; 88 int e; 89 if (InitStack(&s) == OK) 90 for (j = 1; j <= 10; j++) 91 Push(&s, j); 92 printf("栈中元素依次为:\n"); 93 StackTraverse(s); 94 Pop(&s, &e); 95 printf("\n\n弹出的栈顶元素: %d\n", e); 96 printf("\n\n栈空否:%d(1:空 0:否)\n", StackEmpty(s)); 97 GetTop(s, &e); 98 printf("\n\n栈顶元素 e=%d \n栈的长度为%d\n", e, StackLength(s)); 99 ClearStack(&s); 100 printf("\n\n清空栈后,栈空否:%d(1:空 0:否)\n", StackEmpty(s)); 101 102 printf("\n####### 栈 测试是 End ########## \n"); 103 }
main.c:
1 int main() 2 { 3 //LinkListStart(); 4 StackStart(); 5 //LinkStackStart(); 6 getchar(); 7 return 0; 8 }