链表栈

  链表栈的代码已经写了好久了,今天给大家分享出来。

  链表栈还是链表的那几样操作,很简单,把链表搞定,它就不在话下了。不对它做过多介绍了,直接贴代码,水平有限,有错误还请指出。

lstack.h

#ifndef _STACK_H
#define _STACK_H

#define MAXSIZE 10

typedef struct node
{
    int data;
    struct node * next;
} Node;

typedef struct stack
{
    Node * top;
    int size;
} Stack;

void s_init(Stack * stack);//初始化
int s_size(Stack * stack);//栈大小
void s_push(Stack * stack, const int data);//入栈
void s_pop(Stack * stack);//出栈
int s_top(Stack * stack);//栈顶元素
bool s_empty(Stack * stack);//为空
bool s_full(Stack * stack);//为满
void s_destroy(Stack * stack);//销毁

#endif //_STACK_H

lstack.c

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>

#include "lstack.h"

static Node* make_node(const int data);//创建节点
static void destroy_node(Node * current);//销毁节点

void s_init(Stack * stack)
{
    stack->top = make_node(INT_MIN);//创建一个头节点
    stack->size = 0;
}

int s_size(Stack * stack)
{
    return stack->size;
}

void s_push(Stack * stack, const int data)
{
    Node * node;//新节点指针

    assert(stack->size != MAXSIZE);
    node = make_node(data);
    node->next = stack->top;//将新节点next指向栈顶
    stack->top = node;//将栈顶指向新节点

    stack->size++;
}

void s_pop(Stack * stack)
{
    Node * current;//保存栈顶指针
    
    assert(stack->size != 0);
    current = stack->top;
    stack->top = stack->top->next;//栈顶指针下移
    destroy_node(current);

    stack->size--;
}

int s_top(Stack * stack)
{
    return stack->top->data;
}

bool s_empty(Stack * stack)
{
    return stack->size == 0;
}

bool s_full(Stack * stack)
{
    return stack->size == MAXSIZE;
}

void s_destroy(Stack * stack)
{
    Node * current = stack->top;

    while (current != NULL)//遍历链表
    {
        destroy_node(current);
        current = current->next;
    }

    stack->size = -1;
}

static Node* make_node(const int data)
{
    Node * node = (Node *)malloc( sizeof(Node) );
    if ( node == NULL )
        exit(1);

    node->data = data;
    node->next = NULL;

    return node;
}

static void destroy_node(Node * current)
{
    assert(current != NULL);

    free(current);
}

转载于:https://www.cnblogs.com/ITgaozy/p/5146486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值