单链表实现栈数据结构

#ifndef STACK_LINK_
#define STACK_LINK_

#include <stdbool.h>

typedef int  ElementType;
typedef struct _stack_link
{
    ElementType date;
    struct _stack_link *next;
}linkStack;



linkStack* init_link_stack();
bool push(linkStack *stack, int value);//入栈
int pop(linkStack *stack);//出栈
bool display_stack(linkStack *stack);//显示栈内所有元素值
bool isEmpt(linkStack *stack);//判断栈是否为空
int get_stack_length(linkStack *stack);//获取栈中元素的个数

#endif
#include <stdio.h>
#include <stdlib.h>
#include "stack_link.h"

linkStack* init_link_stack()
{
    linkStack* head = (linkStack*)malloc(sizeof(linkStack));
    if(NULL == head){
        perror("malloc failed ...");
        return NULL;
    }
    head->date = 0;
    head->next = NULL;
    
    return head;
}
/*
    fundction: 用链表的头插法模拟入栈操作
    
*/
bool push(linkStack *stack, int value)
{
    if (NULL == stack) {
        perror(" stack hasn't be created ...");
        return false;
    }
    linkStack* node = (linkStack*)malloc(sizeof(linkStack));
    if(NULL == node){
        perror("malloc failed ...");
        return false;
    }
    node->date = value;
    node->next = stack->next;
    stack->next = node;
    return true;
}
/*
用头删法模拟出栈操作
*/
int pop(linkStack *stack)
{
    linkStack *p = NULL;
    int item;
    if(NULL == stack) {
        perror("stack hasn't create");
        return -1;
    }
    if(0 == get_stack_length(stack)) {
        perror("stack is empty.");
        return -1;
    }
    if (stack->next) {
        p = stack->next;
        stack->next = p->next;
        item = p->date;
        free(p);
    }
    return item;
}

int get_stack_length(linkStack *stack)
{
    int len = 0;
    if (NULL == stack) {
        perror("stack is NULL");
        return -1;
    }
    linkStack *p = stack->next;
    while(p) {
        len += 1;
        p = p->next;
    }
    return len;
}
bool isEmpt(linkStack *stack)
{
    if ( !stack || stack->next == NULL)
        return true;
    else
        return false;
}

bool display_stack(linkStack *stack)
{
    if( NULL == stack) {
        perror("stack is null.");
        return false;
    }
    linkStack *p = stack->next;
    while(p) {
        printf(" ---> %d\n", p->date);
        p = p->next;
    }
    return true;
}
int main()
{
    linkStack *stack = init_link_stack();
    /* test code */
    int i = 0;
    for (i = 0; i < 10; i++) {
        push(stack, i);
    }
    display_stack(stack);
    printf("stack len is %d \n",get_stack_length(stack));
    printf("pop date %d \n", pop(stack));
    return;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值