代码:
#include <stdio.h> #include <stdlib.h> #include <conio.h> #define bool int #define false 0 #define true 1 #define ArrayMax 10 #define Empty -1 typedef struct ArrStack { int* val; int base; //栈1底 int top; //栈2底 }TwoStack; /*初始化栈*/ TwoStack* initStack(void) { TwoStack* stack; stack = (TwoStack*)malloc(sizeof(TwoStack)); stack->val = (int*)malloc(sizeof(int)); stack->base = -1; stack->top = ArrayMax; return stack; } /**判断栈1是否为空的条件*/ bool EmptyStack_1(TwoStack* stack) { return stack->base == Empty; } /**判断栈2是否为空的条件*/ bool EmptyStack_2(TwoStack* stack) { return stack->top == ArrayMax; } /** * 判断栈是否满 * */ bool FullStack(TwoStack* stack) { return stack->base + 1 == stack->top; //满足数组大小 } /**栈1-进栈*/ bool PushStack_1(TwoStack* stack, int X) { if(FullStack(stack)) { fprintf(stderr,"Stack overflow! "); return false; } stack->val[++stack->base] = X; return true; } /**栈2-进栈*/ bool PushStack_2(TwoStack* stack, int X) { if(FullStack(stack)) { fprintf(stderr,"Stack overflow! "); return false; } stack->val[--stack->top] = X; return true; } /**栈1-出栈*/ bool PopStack_1(TwoStack* stack) { if(EmptyStack_1(stack)) { return false; } --stack->base; return true; } /**栈2-出栈*/ bool PopStack_2(TwoStack* stack) { if(EmptyStack_2(stack)) { return false; } ++stack->top; return true; } /**获取栈1的顶*/ int GetTopStack_1(TwoStack * stack) { return stack->base; } /**获取栈2的顶*/ int GetTopStack_2(TwoStack * stack) { return stack->top; } int main(void) { TwoStack* Stack; int i; int X; char c; Stack = initStack(); puts("1) 进栈1 2) 进栈2"); puts("3) 出栈1 4) 出栈2"); puts("5) 栈1顶元素 6) 栈2顶元素"); puts("7) 查看栈1 8) 查看栈2"); puts("9) 退出"); while((c = getch()) != '9') { switch(c) { case '1' : printf(" 栈1—输入数据:"); scanf("%d", &X); PushStack_1(Stack, X); break; case '2' : printf(" 栈2—输入数据:"); scanf("%d", &X); PushStack_2(Stack, X); break; case '3' : printf("栈1—出栈 "); PopStack_1(Stack); break; case '4' : printf("栈2—出栈 "); PopStack_2(Stack); break; case '5' : printf("当前栈1—顶元素为: %d ", Stack->val[GetTopStack_1(Stack)]); break; case '6' : printf("当前栈2—顶元素为: %d ", Stack->val[GetTopStack_2(Stack)]); break; case '7' : printf("栈1—所有元素为:"); for(i = 0; i <= GetTopStack_1(Stack); i++) printf("%d ", Stack->val[i]); printf(" "); break; case '8' : printf("栈2—所有元素为:"); for(i = ArrayMax - 1; i >= Stack->top; i--) printf("%d ", Stack->val[i]); printf(" "); break; } } free(Stack); free(Stack->val); return 0; }
时间也不早了,先休息了 = =