|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
下面的代码为了用栈实现使字符串反过来输出
例如 输入 love 输出 evol
为什么能运行,但实现不了,实在看不出来问题在哪,求大佬们解决
#include <stdio.h>
#include <stdlib.h>
#define INIT_STACK_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int StackSize;
}sqStack;
void InitStack ( sqStack *s )
{
s->base = (ElemType *)malloc(INIT_STACK_SIZE * sizeof(ElemType));
if ( !s->base )
{
exit(0);
}
s->top = s->base;
s->StackSize = INIT_STACK_SIZE;
}
void Push ( sqStack *s, ElemType e )
{
if ( s->top - s->base >= s->StackSize )
{
s->base = (ElemType *)realloc(s->base,(INIT_STACK_SIZE + STACKINCREMENT) * sizeof(ElemType));
if ( !s->base )
{
exit(0);
}
s->top = s->base + s->StackSize;
s->StackSize = s->StackSize + STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
void Pop ( sqStack *s, ElemType *e )
{
if ( s->base == s->top )
{
return ;
}
*e = *--(s->top);
}
int LenStack ( sqStack s )
{
return (s.top - s.base);
}
int main()
{
sqStack s;
ElemType c;
int len,i;
InitStack ( &s );
printf("Please input a string and end in '#': \n");
scanf("%c", &c);
while ( c!='# ')
{
Push(&s,c);
scanf("%c",&c);
}
getchar();
printf("\n\n");
len = LenStack (s);
printf("The length of the string are %d\n\n", len);
for ( i=0;i<len;i++ )
{
Pop (&s,&c);
printf("%c", c);
}
return 0;
}
我拷贝你的代码,仅仅在return前加了已经
free(s.base);
运行后可以实现反转
还有一个小地方是你的while循环判定条件应该是
c != '#'
你的代码单引号中多了一个空格
|
|