码迷,mamicode.com
首页 > 其他好文 > 详细

链表栈

时间:2016-01-20 22:10:36      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

链表栈

标签:

原文地址:http://www.cnblogs.com/ITgaozy/p/5146486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!