栈的链式存储

栈的链式存储

源代码

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值