一个同学让我改一段两栈共享的C语言代码,实现进栈、出栈、输出栈里元素的功能。
代码如下:
#include <stdio.h> #include <stdlib.h> #define MaxSize 100 typedef int ElemType; typedef int Status; typedef struct { ElemType data[MaxSize]; int top1; int top2; }Stack, *pStack; //初始化 Status InitStack(pStack S) { S->top1 = -1; S->top2 = MaxSize; return 1; } //入栈函数 Status Push_Stack(pStack S, ElemType e, int stackNumber) { if (S->top1 + 1 == S->top2) return 0; switch (stackNumber) { case 1: S->data[++S->top1] = e; break; case 2: S->data[--S->top2] = e; break; } return 1; } //出栈函数 Status Pop_Stack(pStack S, ElemType *e, int stackNumber) { if (1 == stackNumber) { //判断栈是否为空 if (-1 == S->top1) return 0; *e = S->data[--S->top1]; } else if (2 == stackNumber) { if (MaxSize == S->top2) return 0; *e = S->data[++S->top2]; printf("出栈的元素为:%d ",*e); } return 1; } //输出栈中的元素 Status DispStack(pStack S, int stackNumber) { int i; if (1 == stackNumber) { if (-1 == S->top1){ printf("栈为空! "); return 0; } printf("栈1中的元素为:"); for (i = 0; i <= S->top1; i++) printf("%d ", S->data[i]); printf(" "); printf("栈顶元素为:%d ", S->data[S->top1]); } else if (2 == stackNumber) { if (MaxSize == S->top2){ printf("栈为空! "); return 0; } printf("栈2中的元素为:"); for (i = MaxSize - 1; i >= S->top2; i--) printf("%d ", S->data[i]); printf(" "); printf("栈顶元素为:%d ", S->data[S->top2]); } } int main(void) { Stack S; ElemType e; int n; int tmp; InitStack(&S); for (;;){ printf("请选择要输入哪个栈中的元素 1或2,退出输入请输入3: "); //Visual C++ 2012 使用了更加安全的 run-time library routines 。新的Security CRT functions(就是那些带有“_s”后缀的函数) scanf_s("%d", &n); if (3 == n) { break; } else if(1!=n && 2!=n){ printf("输入错别选项!请选择要输入哪个栈中的元素 1或2,退出输入请输入3: "); } printf("请输入元素值: "); scanf_s("%d", &tmp); if (1 == n || 2 == n) { if (0 == Push_Stack(&S, tmp, n)){ printf("栈已满,不能再添加元素! "); break; } } } while (true){ printf("请选择要输出哪个栈中的元素 1或2: "); scanf_s("%d", &n); if (n == 1) { DispStack(&S, 1); break; } else if (n == 2) { DispStack(&S, 2); break; } else{ printf("输入错误选项! "); } } system("pause"); return 0; }