栈的链式存储
源代码
#include<stdbool.h>
#include <stdio.h>
#include<stdlib.h>
//栈底作为链表头部
typedef struct _node{
int elem;
struct _node* next;
}Stacknode;
typedef struct stack{
Stacknode* top;
Stacknode* bottom;
}Stack;
//初始化栈
bool Stack_init(Stack* l){
l->top=NULL;
l->bottom=NULL;
return true;
}
//判断栈是否为空
bool Stack_Empty(Stack* l){
bool flag=false;
if(l->bottom==NULL)
flag=true;
return flag;
}
//入栈
bool Stack_push(Stack* l,int ele){
bool flag=true;
Stacknode* np=(Stacknode*)malloc(sizeof(Stacknode));
np->elem=ele;
np->next=NULL;
if(np==NULL){
flag=false;
}
else{
if(l->top==NULL){
l->bottom=np;
l->top=np;
}else{
l->top->next=np;
l->top=np;
}
}
return flag;
}
//出栈
bool Stack_Pop(Stack* l,int* ele){
bool flag=true;
Stacknode* np,*sp=l->bottom;
if(Stack_Empty(l))
flag=false;
else{
while(sp->next!=l->top){
sp=sp->next;
}
*ele=l->top->elem;
np=l->top;
l->top=sp;
free(np);
}
return flag;
}
//求栈顶元素
bool Stack_top(Stack* l,int* ele){
bool flag=true;
if(Stack_Empty(l))
flag=false;
else
*ele=l->top->elem;
return flag;
}
//打印栈中元素
bool Stack_print(Stack* l){
bool flag=true;
Stacknode* np=l->bottom;
if(Stack_Empty(l))
flag=false;
else{
while(np){
printf("%d ",np->elem);
np=np->next;
}
}
return flag;
}
int main() {
printf("Hello, World!\n");
bool flag;
int i;//计数器
Stack s;
flag=Stack_init(&s);
for(i=0;i<=4;i++){
flag=Stack_push(&s, i);
}
flag=Stack_print(&s);
printf("\n");
flag=Stack_Pop(&s, &i);
printf("%d\n",i);
flag=Stack_top(&s, &i);
printf("%d\n",i);
return 0;
}