代码:
//用链式存储结构实现链栈
#include<stdio.h>
#include<stdlib.h>
typedef int bool;
#define true 1
#define false 0
typedef struct StackNode{
int data; //数据域
struct StackNode* next; //指针域
}StackNode,*StackNodeNode;
typedef struct LinkStack{
StackNodeNode top; //栈顶指针
int count; //栈顶元素个数
}LinkStack;
bool initLinkStack(LinkStack *S){
if(S==NULL){
return false;
}
S->top=NULL;
S->count=0;
return true;
}
bool clearLinkList(LinkStack *S){
StackNode *temp;
if(S->top==NULL||S->count==0){
return false;
}
while(S->count){
temp=S->top;
S->top=temp->next;
free(temp);
S->count--;
}
return true;
}
bool push(LinkStack *S,int e){
if(S==NULL){
return false;
}
StackNode* temp=(StackNode*)malloc(sizeof(StackNode));
temp->data=e;
temp->next=S->top;
S->top=temp;
S->count++;
return true;
}
bool pop(LinkStack *S,int* e){
if(S==NULL){
return false;
}
StackNode* temp=(StackNode*)malloc(sizeof(StackNode));
*e=S->top->data;
temp=S->top;
S->top=temp->next;
free(temp);
S->count--;
return true;
}
bool printStack(LinkStack S){
if(S.top==NULL||S.count==0){
return false;
}
StackNode* temp=S.top;
while(temp){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
return true;
}
int main(){
LinkStack S;
int e;
initLinkStack(&S);
for(int i=1;i<=5;i++){
push(&S,i);
}
printStack(S);
pop(&S,&e);
printStack(S);
clearLinkList(&S);
return 0;
}
运行结果: