|
|
#2
寒风中的细雨2010-12-18 12:24
程序代码://2个堆栈共用一条内存的问题 #include <stdio.h> #include <stdlib.h> #define MAXNUM 20 #define elemtype int typedef struct { elemtype Stack[MAXNUM]; int LeftTop; int RightTop; }qstype; void InitiateQStack(qstype *s)//初始化 { s->LeftTop=-1; s->RightTop=MAXNUM; } int IsEmpty(qstype s, char WhichStack) { if( WhichStack == 'L' ) { if( s.LeftTop < 0 ) return 1; return 0; } else if ( WhichStack == 'R' ) { if( s.RightTop >= MAXNUM ) return 1; return 0; } else { exit(0); } } int PushQStack(qstype *s,char WhichStack,elemtype x)//进栈 { //if(s->LeftTop>=s->RightTop-1) if( s->LeftTop == s->RightTop-1 ) { printf("堆栈已满\n"); return 0; } if(WhichStack!='L' && WhichStack!='R') { printf("参数错误\n"); return 0; } if(WhichStack == 'L') //s->Stack[++s->LeftTop]==x; s->Stack[++s->LeftTop] = x;//栈顶不为空 else //s->Stack[--(s->RightTop)]==x; s->Stack[--s->RightTop] = x; return 1; } elemtype PopQStack(qstype *s,char WhichStack)//出栈 { if(WhichStack!='L' && WhichStack!='R') { printf("参数错误\n"); return 0; } if(WhichStack=='L') { if(s->LeftTop<0) { printf("左栈已空\n"); return 0; } return s->Stack[(s->LeftTop)--]; } if(WhichStack=='R') { if(s->RightTop>MAXNUM) { printf("右栈已空\n"); return 0; } return s->Stack[(s->RightTop)++]; } } int main() { char WhichStack; qstype *ss = (qstype *)malloc(sizeof(qstype)); elemtype x,y; InitiateQStack(ss); printf("请选择插入左表还是右表: 'L'or 'R':\n"); scanf("%c", &WhichStack); while( scanf("%d",&x)!=EOF ) { //scanf("%d",&x); PushQStack(ss,WhichStack,x); } printf("请选择出栈的表:'L' or 'R':\n"); scanf("%c",&WhichStack); while( !IsEmpty(*ss,WhichStack) ) { y=PopQStack(ss,WhichStack); printf("%d\n",y); } getchar(); getchar(); return 0; } /* 结果运行错误 怎么回事~~~~~~~ */ |
#include <stdio.h>
#include <stdlib.h>
#define MAXNUM 20
#define elemtype int
typedef struct
{
elemtype Stack[MAXNUM];
int LeftTop;
int RightTop;
}qstype;
void InitiateQStack(qstype *s)//初始化
{
s->LeftTop=-1;
s->RightTop=MAXNUM;
}
int PushQStack(qstype *s,char WhichStack,elemtype x)//进栈
{
if(s->LeftTop>=s->RightTop-1)
{
printf("堆栈已满\n");
return 0;
}
if(WhichStack!='L'&&WhichStack!='R')
{
printf("参数错误\n");
return 0;
}
if(WhichStack=='L') s->Stack[++s->LeftTop]==x;
else
s->Stack[--(s->RightTop)]==x;
return 1;
}
elemtype PopQStack(qstype *s,char WhichStack)//出栈
{
if(WhichStack!='L'&&WhichStack!='R')
{
printf("参数错误\n");
return 0;
}
if(WhichStack=='L')
{
if(s->LeftTop<0)
{
printf("左栈已空\n");
return 0;
}
return s->Stack[(s->LeftTop)--];
}
if(WhichStack=='R')
{
if(s->RightTop>MAXNUM)
{
printf("右栈已空\n");
return 0;
}
return s->Stack[(s->RightTop)++];
}
}
int main()
{
char WhichStack;
qstype *ss=(qstype *)malloc(sizeof(qstype));
elemtype x,y;
InitiateQStack(ss);
printf("请选择插入左表还是右表: 'L'or 'R':\n");
scanf("%c",&WhichStack);
while(scanf("%d",&x)!=EOF)
{
scanf("%d",&x);
PushQStack(ss,WhichStack,x);
}
printf("请选择出栈的表:'L' or 'R':\n");
scanf("%c",&WhichStack);
while(PopQStack(ss,WhichStack))
{
y=PopQStack(ss,WhichStack);
printf("%d\n",y);
}
getchar();getchar();
return 0;
}
结果运行错误 怎么回事~~~~~~~
程序代码:
