LiStack.h
#include
#include
#include
#define ElemType char
using namespace std;
typedef struct LinkNode
{
ElemType data;
struct LinkNode *next;
}LiStack;
//初始化
void InitStack(LiStack *s){
s=(LiStack*)malloc(sizeof(LiStack));
s->next=NULL;
}
//销毁
void DestroyStack(LiStack *s){
LiStack *p=s,*q=s->next;
while(q!=NULL){
free(p);
p=q;
q=p->next;
}
free(p);
}
//判空
bool EmptyStack(LiStack *s){
return (s->next==NULL);
}
//进栈
void Push(LiStack *s,ElemType e){
LiStack *p;
p=(LiStack*)malloc(sizeof(LiStack));
p->data=e;
p->next=s->next;
s->next=p;
}
//出栈
bool Pop(LiStack *s){
LiStack *p;
ElemType e;
if(s->next==NULL){
return false;
}
p=s->next;
e=p->data;
s->next=p->next;
free(p);
return true;
}
//取栈顶元素
bool GetPop(LiStack *s){
ElemType e;
if(s->next==NULL){
return false;
}
e=s->next->data;
cout<<"栈顶元素为:";
cout<return true;
}
//输出
bool out(LiStack *s){
ElemType e;
if(s->next==NULL){
return false;
}
LiStack *p=s->next;
while(p!=NULL){
cout<data;
p=p->next;
}
cout<return true;
}
#include
#include "LiStack.h"
using namespace std;
int main() {
LiStack s;
int n,i,a;
ElemType e;
InitStack(&s);
cout<<"请输入需要建立多少个元素的栈:"<>n;
for(i=0;i"请输入建立栈的元素:"<>e;
Push(&s,e);
}
out(&s);
GetPop(&s);
cout<<"是否需要出栈:1.是 2.否"<>a;
if(a=1){
Pop(&s);
out(&s);
GetPop(&s);
}
DestroyStack(&s);
return 0;
}
InitStack这个函数初始化的时候,有问题。
主程序中,LiStack s已经申请了空间,但是在InitStack函数中又重新分配了空间,这么弄是不对的。
修改如下:
//初始化
void InitStack(LiStack* s) {
//s = (LiStack*)malloc(sizeof(LiStack)); //这一句注释掉
s->next = NULL;
}
主函数中,还有一个错误,if(a=1)这里,应该是 if(a==1)
=是赋值运算符,==是逻辑运算符,你少写了一个=