C 语言实现栈数据结构

 


#ifndef STACK_
#define STACK_

#include "stdbool.h"
#include <stdio.h>
#include <stdlib.h>

typedef int ElementType; 
typedef struct stack_node_ {
    ElementType date;
    struct stack_node_ *next;
}stack_node;

typedef struct stack_ {
    stack_node *top;
    stack_node *bottom;
}stack;


bool init_stack(stack *st); //初始化栈
bool push(stack *st, int val);//进栈
bool pop(stack *st, int *val);//出栈
bool isEmpty(stack *st);
void display(stack *st);



#endif
#include "common.h"
#include "stack.h"

bool init_stack(stack *st)
{
    st->top = (stack_node *)malloc(sizeof(stack_node));
    st->bottom = (stack_node *)malloc(sizeof(stack_node));
    if(NULL == st->top || NULL == st->bottom) {
        perror("malloc failed.");
        return false;
    }
    st->bottom = st->top;
    st->top->next = NULL;
    return true;
}
bool isEmpty(stack *st)
{
    if(NULL == st) {
        perror("stack is NULL");
        exit(-1);
    }
    if(st->top == st->bottom) {
        printf("stack is empty...\n");
        return true;
    }
    return false;
}

bool push(stack *st, int val)
{
    stack_node *node = (stack_node *)malloc(sizeof(stack_node));
    if(NULL == node) {
        perror("maolloc failed.");
        return false;
    }
    node->date = val;
    node->next = st->top;
    st->top = node;
    return true;    
}

bool pop(stack *st, int *val)
{
    if (isEmpty(st)) {
        printf("Don't have date in stack.\n");
        return false;
    }

    stack_node *tmp = st->top;
    *val = tmp->date;
    st->top = tmp->next;
    free(tmp); //释放弹出数据内存
    tmp = NULL;
    
    return true;   
}

void display(stack *st)
{
    if (NULL == st) {
        perror("stack is NULL.");
        exit(1);
    }
    stack_node *tmp = st->top;
    while(tmp != st->bottom) {
        printf("---> %d\n", tmp->date);
        tmp = tmp->next;
    }
}
int main()
{
    stack st;
    int val;
    init_stack(&st);
    printf("whether stack is empty %d\n", isEmpty(&st));
    push(&st, 10);
    push(&st, 20);
    pop(&st, &val);
    printf("val --> %d\n", val);
    display(&st);
    
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值