数组
取自《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指针的思路来写栈,这样实现出来的栈,不同栈对象的储存、操作互不干扰,可在程序中使用多个栈