链式栈无法进行压栈和出栈
#include
#include
#include
typedef char DataType;
typedef struct Node{
DataType ele;
struct Node *link;
}StackNode;
void initStack(StackNode *S){
S=NULL;
}
bool pushStack(StackNode *S,DataType data){
StackNode *p =(StackNode*)malloc(sizeof(StackNode));
if(p==NULL){
printf("创建节点失败\n");
return false;
exit(1);
}
p->ele=data;
p->link=S;
S=p;
return true;
}
bool isEmpty(StackNode *S){
if(S==NULL){
return true;
}else{
return false;
}
}
bool pop(StackNode *S,DataType *x){
if(isEmpty(S)){
return false;
}
StackNode *p=S;
*x=p->ele;
S=p->link;
return true;
}
int main()
{
StackNode S;
char x;
pushStack(&S,'o');
printf("%c",S.ele);
return 0;
}
供参考:
#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>
typedef char DataType;
typedef struct Node{
DataType ele;
struct Node *link;
}StackNode;
void initStack(StackNode *S){
S->link = NULL; //S=NULL;
}
bool pushStack(StackNode *S,DataType data){
StackNode *p =(StackNode*)malloc(sizeof(StackNode));
if(p==NULL){
printf("创建节点失败\n");
return false;
//exit(1);
}
p->ele=data;
p->link = S->link; //p->link = S;
S->link = p; //S=p;
return true;
}
bool isEmpty(StackNode *S){
if(S->link == NULL){ //if(S==NULL)
return true;
}else{
return false;
}
}
bool pop(StackNode *S,DataType *x){
if(isEmpty(S)){
return false;
}
StackNode *p=S->link; //*p=S;
*x=p->ele;
S->link=p->link; //S=p->link;
free(p); //修改
return true;
}
int main()
{
StackNode S;
char x;
initStack(&S); //初始化栈
//压栈
pushStack(&S,'a');
pushStack(&S,'b');
pushStack(&S,'c');
pushStack(&S,'d');
//弹栈
if (pop(&S,&x))
printf("%c",x);
else
printf("\nisEmpty");
if (pop(&S,&x))
printf("%c",x);
else
printf("\nisEmpty");
if (pop(&S,&x))
printf("%c",x);
else
printf("\nisEmpty");
if (pop(&S,&x))
printf("%c",x);
else
printf("\nisEmpty");
if (pop(&S,&x))
printf("%c",x);
else
printf("\nisEmpty");
if (pop(&S,&x))
printf("%c",x);
else
printf("\nisEmpty");
//printf("%c",S.ele);
return 0;
}