栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c语言栈的实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c语言栈的实现

  1. 只实现了int,不会通用的
  2. 节点包含三个元素,next,value,count,我的电脑结构体反正用的内存对齐,一个指针一个int 16字节,一个指针两个int还是16字节
  3. 链表节点从头部插入,也就是说链表指针始终指向栈顶,麻烦就是有些操作需要取地址,解决方法可以用个不放数据的头节点
#include
#include

typedef struct Stacknode {
	struct Stacknode* next;
	int value;
	int count;
}stacknode;

void init(stacknode** stack, int value);
void display(stacknode* stack);
int get_top(stacknode* stack);
int pop(stacknode** stack);
void push(stacknode** stack, int num);
void destroy(stacknode** stack);

void main() {
	stacknode* stack = NULL;
	init(&stack, 1);
	init(&stack, 2);
	init(&stack, 3);
	display(stack);
	printf("get_top %dn", get_top(stack));
	printf("pop %dn", pop(&stack));
	display(stack);
	push(&stack, 4);
	printf("pushn");
	display(stack);
	destroy(&stack);
	display(stack);
}

void init(stacknode** stack,int value) {
	stacknode* p = (stacknode*)malloc(16);
	if (!p) {
		printf("errorn");
		exit(1);
	}
	p->value = value;
	if (*stack==NULL) {
		*stack = p;
		(*stack)->next = NULL;
		(*stack)->count = 1;
	}
	else {
		p->next = *stack;
		p->count = (*stack)->count+1;
		*stack = p;
	}
}

void display(stacknode* stack) {
	if (!stack) 
		printf("栈空n");
	while (stack) {
		printf("display %d %dn", stack->value,stack->count);
		stack=stack->next;
	}
	printf("n");
}

//返回栈顶元素
int get_top(stacknode* stack) {
	if (!stack) {
		printf("栈空n");
		exit(1);
	}
	else
		return stack->value;
}

//弹出并返回栈顶元素
int pop(stacknode** stack) {
	if (!stack) {
		printf("栈空n");
		exit(1);
	}
	else {
		int ans = (*stack)->value;
		stacknode* p = (*stack);
		*stack = (*stack)->next;
		if (p)
			free(p);
		return ans;
	}
}

//压入元素
void push(stacknode** stack, int num) {
	stacknode* node = (stacknode*)malloc(16);
	if (!node) {
		printf("errorn");
		exit(1);
	}
	node->value = num;
	if (*stack) {
		node->count = (*stack)->count + 1;
		node->next = *stack;
	}
	else {
		node->count = 1;
		node->next = NULL;
	}
	*stack = node;
}

//清空栈
void destroy(stacknode** stack) {
	if (!*stack)
		printf("栈空n");
	while (*stack) {
		stacknode* p = *stack;
		*stack = (*stack)->next;
		free(p);
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012369.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号