资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

数据结构之栈c语言实现

    栈是一种先进后出的数据结构,计算机中常见的函数调用就用到了这种结构,其常用的操作就是出栈、入栈,如下图,数据总是从栈顶入,从栈顶出:

创新互联建站专注于官渡网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供官渡营销型网站建设,官渡网站制作、官渡网页设计、官渡网站官网定制、微信小程序定制开发服务,打造官渡网络公司原创品牌,更为您提供官渡网站排名全网营销落地服务。

    

数据结构之栈c语言实现

    接下来看一个简单的程序将按“abcdef”入栈,并打印其出栈顺序:

#include 
#include 
#include 

#define STACK_SIZE        16
#define NAME_MAX_SIZE     32
#define ERR		  -1
#define SUCC		  0

typedef struct stack {
	char *array;	/* 栈的起始地址 */
	int stack_size;	/* 栈大小 */
	int top;	/* 栈顶所在的位置 */
	char(*pop)(struct stack *sta);	/* 出栈 */
	int (*push)(struct stack *sta, char data); /* 入栈 */
} stack_t;

static int is_empty(stack_t *sta)
{
	return (sta->top == -1);
}

static int is_full(stack_t *sta)
{
	return (sta->top == sta->stack_size-1);
}

/* 将栈顶元素出栈,并返回 */
char pop_stack(stack_t *sta)
{
	char ch;

	if (is_empty(sta)) {
		printf("the stack is empty \n");
		return ERR;
	}

	ch = sta->array[sta->top];
	--sta->top;

	return ch;
}

/* 在栈顶插入元素 */
int push_stack(stack_t *sta, char data)
{
	if (is_full(sta)) {
		printf("the stack is full \n");
		return ERR;
	}

	++sta->top;
	sta->array[sta->top] = data;

	return SUCC;
}

void init_stack(stack_t **sta)
{
	*sta = (stack_t *)malloc(sizeof(stack_t));
	if ((*sta) == NULL) {
		printf("no mem \n");
		return ;
	}

	(*sta)->top        = -1;
	(*sta)->stack_size = STACK_SIZE;
	(*sta)->pop        = pop_stack;
	(*sta)->push       = push_stack; 
	(*sta)->array = (char *)malloc(STACK_SIZE);
	if ((*sta)->array == NULL) {
		printf("no mem \n");
		return ;
	}
}

int main(int argc, char *argv[])
{
	int size, ret, i;
	stack_t *sta_addr;
	char data[] = "abcdef";
	
	init_stack(&sta_addr);
	size = sizeof(data) / sizeof(data[0]);

	for (i = 0; i < size; i++) {
		sta_addr->push(sta_addr, data[i]);
	}
	
	while (1) {
		 ret = sta_addr->pop(sta_addr);
		 if (ret != ERR) {
			printf("%c,", ret);
		 } else {
			break;
		 }
	}

	return 0;
}

分享文章:数据结构之栈c语言实现
本文网址:http://cdkjz.cn/article/piejoc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220