#include <stdio.h>
#include <stdlib.h>//malloc,free需要用到头文件
#include<stdbool.h>//bool型的头文件
#define len 6//栈初始容量
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LiStack;
//初始化链栈
void IniteStack(LiStack &S){
S=(LNode*)malloc(sizeof(LNode));
S->next=NULL;
}
//判空
bool StackEmpty(LiStack S){
if(S->next==NULL)
return true;
else return false;
}
//进栈
bool Push(LNode *&S,int x){
LNode *p;
p=(LNode*)malloc(sizeof(LNode));
p->next=NULL;/*天勤书:加上这一条件,每当申请新节点,
指针域指向NULL,可以避免一些错误,养成好习惯
*/
p->data=x;
p->next=S->next;
S->next=p;
return true;
}
//出栈
bool Pop(LNode *&S,int &x){
if(StackEmpty(S)) return false;
LNode *p=S->next;
x=p->data;
S->next=p->next;
free(p);
return true;
}
int main(){
LiStack S;
IniteStack(S);
LNode *p=S->next;
int x,i=0;
while(i<len){
scanf("%d",&x);
Push(S,x);//
i++;
}
// while(i<len){
// Pop(S,x);
// printf("输出[%d]",x);
// i++;
// }
while(S->next)
{ Pop(S,x);
printf("输出[%d]",x);
}
}
运行结果
1
2
3
4
5
6
输出[6]输出[5]输出[4]输出[3]输出[2]输出[1]
链栈的出栈/入栈操作
最新推荐文章于 2023-11-11 00:10:14 发布