栈实现

数组

取自《C专家编程》

#define MAXSIZE 100

int top = -1;
int stack[MAXSIZE];

#define pop stack[top--]
#define push(s) stack[++top] = s

出栈入栈如此之简洁……

链表

stack.h

#ifndef STACK
#define STACK

#define node_type int

typedef struct node{
    node_type value;
    struct node *next;
}node_t;

typedef struct s{
    node_t *first;
    void (*push)(node_type, struct s *);
    void (*pop)(struct s *);
    node_type (*top)(struct s *);
    int (*is_empty)(struct s *);
}stack;

void creat_stack(stack *s);

#endif // !STACK

stack.c

#include <malloc.h>
#include <assert.h>
#include "stack.h"

static void push(node_type val, stack *s);
static void pop(stack *s);
static node_type top(stack *s);
static int is_empty(stack *s);

static void push(node_type val, stack *s)
{
    node_t *newnode=NULL;
    newnode = (node_t *)malloc(sizeof(node_t));
    assert(NULL != newnode);

    newnode->value = val;
    newnode->next = s->first;
    s->first = newnode;
}

static void pop(stack *s)
{
    assert(!s->is_empty(s) );

    node_t *f = s->first;
    s->first = s->first->next;
    free(f);
}

static node_type top(stack *s)
{
    assert(!s->is_empty(s));

    return s->first->value;
}

static int is_empty(stack *s)
{
    return (NULL == s->first );
}

void creat_stack(stack *s)
{
    s->push = push;
    s->pop = pop;
    s->top = top;
    s->is_empty = is_empty;
    s->first = NULL;
}

使用

#include <stdio.h>
#include "stack.h"

#define dout(d)   printf("%d    ",d)

int main()
{
    stack s1,s2;
    creat_stack(&s1);
    creat_stack(&s2);
    s1.push(1, &s1);
    s1.push(2, &s1);
    s1.push(4, &s1);
    s2.push(3, &s2);
    s2.push(6, &s2);
    s2.push(9, &s2);
    while(!s1.is_empty(&s1)){
        dout(s1.top(&s1));
        s1.pop(&s1);
    }
    printf("\r\n");
    while (!s2.is_empty(&s2))
    {
        dout(s2.top(&s2));
        s2.pop(&s2);
    }
    printf("\r\n");

    return 0;
}

运行结果:
运行结果

  • 学习C++中this指针的思路来写栈,这样实现出来的栈,不同栈对象的储存、操作互不干扰,可在程序中使用多个栈
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值