链式栈的C实现

链式栈不用考虑栈空间为满的情况,不存在向上溢出。

Linux上编译有个warning说的是int 和 void*之间的转换,而事实上在32bits机器上这两者之间是可以相互转换的,而测试在64bits系统上就会存在这个提示。不知道大家有什么好的解决办法?

实现代码如下:

头文件:

#ifndef LINK_STACK_H_INCLUDED
#define LINK_H_INCLUDED


typedef void* Element;
// top points to the top node of the stack
typedef struct l_stack_node
{
    Element data;
    struct l_stack_node *next;
}l_stack_node, *lnode;


typedef struct l_stack
{
    l_stack_node* top;
    int count;
}l_stack, *pstack;


pstack init_stack();
lnode init_lnode();
int is_empty(pstack ps);
Element get_top(pstack ps);
Element pop(pstack ps);
pstack push(pstack ps, Element e);
void display_stack(pstack ps);

#endif // LINK_STACK_H_INCLUDED

实现文件:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "link_stack.h"

#define TRUE        0
#define FALSE       1

pstack init_stack()
{
    pstack ps;
    if((ps = (pstack)malloc(sizeof(l_stack))) == NULL){
        printf("Init link stack error\n");
        return NULL;
    }
    ps->top = NULL;
    ps->count = 0;    
    return ps;
}

lnode init_lnode()
{
    lnode node;
    if((node = (lnode)malloc(sizeof(l_stack_node))) == NULL){
        printf("Init link node error\n");
    }
    node->next = NULL;
    // if node points to NULL then return NULL
    return node;
}

int is_empty(pstack ps)
{
    return ((ps->count <= 0)?TRUE : FALSE);
}

Element get_top(pstack ps)
{
    if(is_empty(ps) == 0)
    {
        printf("Link stack is empty\n");
        return NULL;
    }
    else
        return ps->top->data;
}

int get_count(pstack ps)
{
    if(ps != NULL)
        return ps->count;
    else
        return 0;
}

Element pop(pstack ps)
{
    if(ps->count <= 0)
        return NULL;
    lnode n = ps->top;
    ps->top = n->next;
    ps->count--;
    return n->data;   
}

pstack push(pstack ps, Element e)
{
    lnode node = init_lnode();
    node->data = e;
    node->next = ps->top;
    ps->top = node;
    ps->count++;
    return ps;
}

void display_stack(pstack ps)
{
    lnode t = ps->top;
    if(is_empty(ps) == 0)
        printf("Link stack is empty\n");
    else
    {
        while(t != NULL)
        {
            printf("%d ", t->data);
            t = t->next;
        }
        printf("\n");
    }
}

测试文件:

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

int main()
{
    int i;
    int arr[] = {1,2,3,4,5,6,7,8};
    int len = 8;
    pstack ps = init_stack();
    for(i=0; i<len; i++)
        ps = push(ps, arr[i]);
    display_stack(ps);
    int n = pop(ps);
    display_stack(ps);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值