数据结构示例之用链表实现栈

以下是“使用链表实现栈”的简单示例:

1. 用c语言实现的版本

#include<stdio.h>
#include<stdlib.h>

struct s_node
{
	int data;
	struct s_node *next;
};

typedef struct s_node* pNode;
pNode stack = NULL;
int pCount = 0;

/* 打印栈的内容 */
void print_stack()
{
	pNode temp = NULL;
	temp = stack;
	if (temp == NULL)
	{
		printf("The stack is empty!\n");
	}
	else
	{
		while (temp != NULL)
		{
			printf("[%d]", temp->data);
			temp = temp->next;
		}
		printf("\n");
	}
}

/* 入栈,从头部插入 */
void push(int value)
{
	if (stack)
	{
		pNode newnode;
		newnode = (pNode)malloc(sizeof(s_node)); 
		if (!newnode)
		{
			printf("malloc fail, please check!");
			return;
		}
		newnode->data = value;
		newnode->next = stack;
		stack = newnode;
		++pCount;
	}
	else
	{
		stack = (pNode)malloc(sizeof(s_node));
		if (!stack)
		{
			printf("malloc fail, please check!");
			return;
		}
		stack->data = value;
		stack->next = NULL;
		++pCount;
	}
}

/* 出栈,从头部删除 */
void pop(int *value)
{
	pNode top;

	if (stack != NULL)
	{
		top = stack;
		stack = stack->next;
		*value = top->data;
		free(top);
		--pCount;
	}
	else
	{
		pCount = 0;
	}
}

void main()
{
	pNode point;
	int select;
	int value;

	printf("(1)Input a stack data.\n");
	printf("(2)Output a stack data.\n");
	printf("(3)Exit\n");
	printf("Please select your choice: ");
	scanf("%d", &select);
	do
	{
		switch (select)
		{
		case 1:
			printf("Before push, the stack content (top->bottom) is: \n");
			print_stack(); /* 打印栈的内容 */
			printf("Please input the digit: ");
			scanf("%d", &value);
			push(value);
			printf("After push, the stack content (top->bottom) is: \n");
			print_stack();
			break;
		case 2:
			printf("Before pop, the stack content (top->bottom) is: \n");
			print_stack(); /* 打印栈的内容 */
			if (pCount) {
				pop(&value);
				printf("The output value is: [%d].\n", value);
				printf("After pop, the stack content (top->bottom) is: \n");
				print_stack();
			}
			else
			{
				printf("The stack is empty, it can not be poped!");
			}
			break;
		default:
			printf("Please input the right choice!");
			break;
		}

		printf("\n(1)Input a stack data.");
		printf("\n(2)Output a stack data.");
		printf("\n(3)Exit.");
		printf("\nPlease select your choice: ");
		scanf("%d", &select);
	} while (select != 3);
}

运行结果如下所示:



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值