链式栈实现:
#include <stdio.h>
struct node
{
int val;
struct node *next;
};
typedef struct node Node;
Node *base, *top;
void init_stack()
{
base = top = NULL;
}
void push_stack(Node *newnode)
{
if(base == top)
{
base = newnode;
top = (Node*) malloc(sizeof(Node));
top->next = newnode;
}
newnode->next = top->next;
top->next = newnode;
printf("%d\n", newnode->val); //入栈顺序
}
int pop_stack()
{
int temp;
Node *tp = top;
if(base == NULL)
printf("stack is empty!\n");
temp = top->next->val;
top = top->next;
free(tp);
return temp;
}
void show() //用于检验出栈是否正确,不属于栈的实现
{
Node *p = top->next;
while(p != base)
{
printf("%d ", p->val);
p = p->next;
}
printf("%d ", p->val);
putchar(10);
}
int main()
{
init_stack();
int i = 0;
Node *newnode;
for(i = 0; i < 5; i++)
{
newnode = (Node*) malloc(sizeof(Node));
if(newnode)
{
newnode->val = i;
push_stack(newnode);
}
}
show(); //入栈后,从栈顶到栈底的数据
printf("%d\n", pop_stack()); //取一个数
show(); //出栈一个数后,从栈顶到栈底的数据
return 0;
}
顺序栈的实现:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100 //栈的初始化大小
#define STACK_INCREASE 20 //栈的扩容
struct stack
{
int *base; //栈存放的数据类型,根据需要选择
int *top;
int stacksize; //栈的大小
};
typedef struct stack Stack;
void create_stack(Stack **s) //创建一个空栈
{
*s = (Stack*) malloc(sizeof(Stack));
if(!*s)
puts("create stack failed");
}
void stack_init(Stack *s) //初始化栈
{
s->base = (int*) malloc(sizeof(int) * STACK_INIT_SIZE);
if(!(s->base))
return;
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
void push_stack(Stack *s, int a)
{
if(s->top - s->base >= s->stacksize) //栈满扩容
{
s->base = (int*) realloc(s->base, (s->stacksize+STACK_INCREASE)*sizeof(int));
}
if(!(s->base)) //扩容失败
{
puts("realloc failed");
return;
}
s->top = s->base + s->stacksize; //栈顶指针重新定位至扩充后的内容
s->stacksize += STACK_INCREASE; //栈大小重新赋值
*s->top = a; //入栈
s->top++;
// printf("pop stack %d\n", a);
}
void pop_stack(Stack* s) //出栈
{
if(s->top == s->base) //栈空
return;
s->top--;
// printf("%d\n", *s->top);
}
int main()
{
Stack *s;
create_stack(&s);
stack_init(s);
push_stack(s, 5);
pop_stack(s);
return 0;
}