主题:顺序栈的问题
shohokuf
[专家分:0] 发布于 2006-05-30 15:50:00
下面是我的源程序:
在运行的时候出现了内存不可written 的问题.指教是什么原因?
//栈的顺序存储
#include<stdio.h>
typedef char ElemType;
#define MaxSize 100
typedef struct{
ElemType stack[MaxSize];
int top;
}stacktype;
void initstack(stacktype *s)
{
s->top=-1;
}
void push(stacktype *s,ElemType x)
{
if(s->top==MaxSize)printf("STACK IS FULL!\n");
else
s->top++;
s->stack[s->top]=x;
}
void pop(stacktype *s)
{
if (s->top==-1)printf("STACK IS EMPTY!\n");
else
s->top--;
}
ElemType gettop(stacktype *s)
{
if (s->top==-1)printf("STACK IS EMPTY!\n");
else
return(s->stack[s->top]);
}
int empty(stacktype *s)
{
if (s->top==-1)return 1;
else return 0;
}
void display(stacktype *s)
{
int i;
for(i=s->top;i>=0;i--)
printf("%c",s->stack[i]);
printf("\n");
}
main()
{
stacktype *st;
printf("建立一空栈:\n");
initstack(st);
printf("栈是否为空(0代表否;1代表是):%d",empty(st));
printf("进栈a,b,c,d:\n");
push(st,'a');
push(st,'b');
push(st,'c');
push(st,'d');
printf("栈中的元素有:");
display(st);
printf("\n出一次栈:");
pop(st);
printf("栈顶元素是:%c",gettop(st));
display(st);
}
回复列表 (共3个回复)
沙发
rickone [专家分:15390] 发布于 2006-06-02 23:49:00
void push(stacktype *s,ElemType x)
{
if(s->top==MaxSize)printf("STACK IS FULL!\n");
else
s->top++;
s->stack[s->top]=x;
}
改成
void push(stacktype *s,ElemType x)
{
if(s->top==(MaxSize-1))printf("STACK IS FULL!\n");
else
s->top++;
s->stack[s->top]=x;
}
板凳
shohokuf [专家分:0] 发布于 2006-06-04 15:08:00
我在vc 上运行了之后还是不行啊?
3 楼
wbyoulove [专家分:4830] 发布于 2006-06-04 22:20:00
#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
#define MaxSize 100
typedef struct{
ElemType stack[MaxSize];
int top;
}stacktype;
void initstack(stacktype *s)
{
s->stack[MaxSize]=NULL;
s->top=-1;
}
void push(stacktype *s,ElemType x)
{
if(s->top==MaxSize)printf("STACK IS FULL!\n");
else
s->top++;
s->stack[s->top]=x;
}
void pop(stacktype *s)
{
if (s->top==-1)printf("STACK IS EMPTY!\n");
else
s->top--;
}
ElemType gettop(stacktype *s)
{
if (s->top==-1)printf("STACK IS EMPTY!\n");
else
return(s->stack[s->top]);
}
int empty(stacktype *s)
{
if (s->top==-1)return 1;
else return 0;
}
void display(stacktype *s)
{
int i;
for(i=s->top;i>=0;i--)
printf("%c",s->stack[i]);
printf("\n");
}
main()
{
stacktype *st;
st=(stacktype *) malloc(100*sizeof(stacktype)); //没分配内存
printf("建立一空栈:\n");
initstack(st);
printf("栈是否为空(0代表否;1代表是):%d",empty(st));
printf("进栈a,b,c,d:\n");
push(st,'a');
push(st,'b');
push(st,'c');
push(st,'d');
printf("栈中的元素有:");
display(st);
printf("\n出一次栈:");
pop(st);
printf("栈顶元素是:%c",gettop(st));
display(st);
}
我来回复