c语言
#include
#include<Windows.h>
#include
#define StackSize 100
//定义栈
struct SeqStack
{
char data[StackSize];
int top;
};
//置空栈
void InitStack(struct SeqStack *s)
{
s->top=-1;
}
//判空栈
int StackEmpty(struct SeqStack *s)
{
if( s->top==-1)
return 1;
else
{
printf("栈不为空");
return 0;
}
}
//判满栈
int StackFull(struct SeqStack *s)
{
if(s->top==StackSize-1)
{
return 1;
}
else
{
return 0;
}
}
//进栈
void Push(struct SeqStack *s,char x)
{
if(StackFull(s))
printf("栈已满");
else
s->data[++s->top]=x;
}
//退栈
char Pop(struct SeqStack *s)
{
if(StackEmpty(s))
printf("栈已空");
else
return s->data[s->top--];
}
//遍历栈
void PrintfStack(SeqStack *s){
for(int i=0;itop;i++)
printf("s%",s->data[i]);
}
int main()
{
struct SeqStack *l;
InitStack(l);
Push(l,1);
Push(l,2);
Push(l,3);
Push(l,4);
Push(l,5);
PrintfStack(l);
}
“Pop”: 不是所有的控件路径都返回值
使用了未初始化的局部变量“l”
是没有初始化指针,给他分配内存空间吗?
如果要如何操作,这方面知识盲区
修改处见注释,供参考:
#include<stdio.h>
#include<stdlib.h>
//#include<Windows.h>
//#include<math.h>
#define StackSize 100
//定义栈
struct SeqStack
{
char data[StackSize];
int top;
};
//置空栈
void InitStack(struct SeqStack **s)// (struct SeqStack *s)修改
{
(*s)=(struct SeqStack*)malloc(sizeof(struct SeqStack));//修改
(*s)->top=-1; //修改
}
//判空栈
int StackEmpty(struct SeqStack *s)
{
if( s->top==-1)
return 1;
else
{
printf("栈不为空");
return 0;
}
}
//判满栈
int StackFull(struct SeqStack *s)
{
if(s->top==StackSize-1)
{
return 1;
}
else
{
return 0;
}
}
//进栈
void Push(struct SeqStack *s,char x)
{
if(StackFull(s))
printf("栈已满");
else
s->data[++s->top]=x;
}
//退栈
char Pop(struct SeqStack *s)
{
if(StackEmpty(s))
printf("栈已空\n");
else
return s->data[s->top--];
}
//遍历栈
void PrintfStack(SeqStack *s){
for(int i=0;i<=s->top;i++) //(int i=0;i<s->top;i++)
printf("%c ",s->data[i]); //printf("s%",s->data[i]);
printf("\n"); //修改
}
int main()
{
struct SeqStack* l;
InitStack(&l); //修改 InitStack(l);
Push(l,'1'); //修改
Push(l,'2');
Push(l,'3');
Push(l,'4');
Push(l,'5');
PrintfStack(l);
printf("%c",Pop(l)); //修改
printf("%c",Pop(l));
printf("%c",Pop(l));
printf("%c",Pop(l));
printf("%c",Pop(l));
printf("%c",Pop(l));
return 0;
}
struct SeqStack *l; l只是个指针,并没有分配内存。在使用前先用malloc分配内存