C语言学习:通过链表来实现栈

接上例:http://blog.csdn.net/kunshan_shenbin/article/details/18903731

stack.h还是上例中的代码,不需要变化。

stack.c代码如下:

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

typedef struct STACK_NODE {
	STACK_TYPE value;
	struct STACK_NODE *next;
} StackNode;

static StackNode *stack = NULL;

void create_stack(size_t size) {}

void destroy_stack(void) {

	while(!is_empty()) {
		pop();
	}
}

void push(STACK_TYPE value) {

	StackNode *stack_node = (StackNode *) malloc(sizeof(StackNode));
	if(stack_node == NULL) {
		printf("failed to initialize slack node");
		exit(-1);
	}
	stack_node->value = value;
	stack_node->next = stack;
	stack = stack_node;
}

STACK_TYPE pop(void) {

	if(is_empty()) {
		printf("stack is already empty");
		exit(-1);
	}
	StackNode *stack_node = stack;
	STACK_TYPE stack_value = stack_node->value;
	stack = stack_node->next;
	free(stack_node);
	return stack_value;
}

int is_empty(void) {

	return stack == NULL;
}

int is_full(void) {

	return 0;
}

void print(void) {

	StackNode *stack_node = stack;
	while(stack_node != NULL)
	{
		printf("%d ", stack_node->value);
		stack_node = stack_node->next;
	}
	printf("\n");
}

int main() {

	create_stack(3);
	push(1);
	push(2);
	push(3);
	push(4);
	print();

	printf("%d\n",pop());
	printf("%d\n",pop());
	printf("%d\n",pop());

	print();

	printf("%d\n",pop());
	printf("%d\n",pop());

	print();

	destroy_stack();

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值