1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 20
typedef struct { int data[MAXSIZE]; int top1; int top2; } SqDoubleStack;
int InitStack(SqDoubleStack *S) { S->top1 = -1; S->top2 = MAXSIZE; return OK; }
int Push(SqDoubleStack *S, int e, int stackNumber) { if (S->top1 + 1 == S->top2) return ERROR;
if (stackNumber == 1) S->data[++S->top1] = e; else if (stackNumber == 2) S->data[--S->top2] = e; return OK; } int StackTraverse(SqDoubleStack S) { for (int i = 0; i < S.top1; i++) printf("%d ", S.data[i]);
for (int i = S.top2; i < MAXSIZE; i++) printf("%d ", S.data[i]);
printf("\n"); return OK; }
int StackEmpty(SqDoubleStack S) { if (S.top1 == -1 && S.top2 == MAXSIZE) return TRUE; else return FALSE; }
int StackLength(SqDoubleStack S) { return (S.top1 + 1) + (MAXSIZE - 1 - S.top2); }
int Pop(SqDoubleStack *S, int *e, int stackNumber) { if (stackNumber == 1) { if (S->top1 == -1) return ERROR;
*e = S->data[S->top1]; S->top1--; } else if (stackNumber == 2) { if (S->top2 == MAXSIZE) return ERROR;
*e = S->data[S->top2]; S->top2++; } return OK; } int main() { int j, e; SqDoubleStack s;
if (InitStack(&s) == OK) { for (j = 1; j <= 5; j++) Push(&s, j, 1); for (j = MAXSIZE; j >= MAXSIZE - 2; j--) Push(&s, j, 2); }
printf("栈中元素依次为:"); StackTraverse(s);
printf("当前栈中元素有:%d \n", StackLength(s));
Pop(&s, &e, 2); printf("弹出的栈顶元素 e=%d\n", e); printf("栈空否:%d(1:空 0:否)\n", StackEmpty(s));
for (j = 6; j <= MAXSIZE - 2; j++) Push(&s, j, 1); printf("栈中元素依次为:"); StackTraverse(s);
printf("栈满否:%d(1:否 0:满)\n", Push(&s, 100, 1));
InitStack(&s); printf("清空栈后,栈空否:%d(1:空 0:否)\n", StackEmpty(s));
return 0; }
|