顺序栈
1 /* 2 顺序栈 3 LJK 2018-07-03 4 */ 5 6 #include<stdio.h> 7 8 #define MAXSIZE 15 9 #define OK 1 10 #define ERROR 0 11 #define TRUE 1 12 #define FALSE 0 13 14 typedef int SElemType; 15 typedef int Status; 16 17 typedef struct sqStack 18 { 19 SElemType data[MAXSIZE]; // 数组,存放数据元素 20 int top; // 用于栈顶指针 21 }SqStack; 22 23 // 构造一个空栈 24 Status InitStack(SqStack *S) 25 { 26 S->top = -1; 27 return OK; 28 } 29 30 // 压栈操作 31 Status Push(SqStack *S, SElemType e) 32 { 33 if (S->top == MAXSIZE - 1) return ERROR; // 栈满 34 S->data[++S->top] = e; 35 return OK; 36 } 37 38 // 出栈操作 39 Status Pop(SqStack *S, SElemType *e) 40 { 41 if (S->top == -1) return ERROR; // 空栈 42 *e = S->data[S->top--]; 43 return OK; 44 } 45 46 // 遍历元素 47 Status StackTraverse(SqStack S) 48 { 49 int i = 0; 50 while (i<=S.top) 51 { 52 printf("%d ", S.data[i++]); 53 } 54 printf("\n"); 55 return OK; 56 } 57 58 Status StackEmpty(SqStack S) 59 { 60 if (S.top == -1) return TRUE; 61 else return ERROR; 62 } 63 64 Status GetTop(SqStack S, SElemType *e) 65 { 66 if (S.top == -1)return ERROR; 67 else *e = S.data[S.top]; 68 return OK; 69 } 70 71 Status ClearStack(SqStack *S) 72 { 73 S->top = -1; 74 return OK; 75 } 76 77 int StackLength(SqStack S) 78 { 79 return S.top + 1; 80 } 81 82 int main() 83 { 84 SqStack s; 85 int j; 86 SElemType e; 87 88 if (InitStack(&s) == OK) 89 { 90 for (j = 1; j <= 10; j++) 91 Push(&s, j); 92 } 93 printf("栈中元素依次为:"); 94 StackTraverse(s); 95 printf("\n"); 96 97 Pop(&s, &e); 98 printf("弹出栈顶元素:%d", e); 99 printf("栈中元素依次为:"); 100 StackTraverse(s); 101 printf("\n"); 102 103 printf("栈是否空:%d (1:空 0:否)\n", StackEmpty(s)); 104 printf("\n"); 105 106 GetTop(s, &e); 107 printf("栈顶元素e = %d,栈的长度为:%d\n", e, StackLength(s)); 108 printf("\n"); 109 110 ClearStack(&s); 111 112 printf("清空栈后,栈是否为空:%d (1:空 0:否)", StackEmpty(s)); 113 printf("\n"); 114 115 getchar(); 116 return 0; 117 }