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