数据结构示例之使用数组实现栈

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

1. 用c语言实现的版本

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

#define MaxSize 10
int stack[MaxSize];
int top = -1;

/* 入栈 */
void push(int value)
{
	int i;
	if (top >= MaxSize-1)
	{
		printf("\nThe stack is full!\n");
	}
	else
	{
		printf("Before push,the stack content is (top->bottom): \n");
		if (top < 0) {
			printf("It is empty.");
		}
		else {
			for (i = top; i >= 0; --i)
			{
				printf("%d ", stack[i]);
			}
		}
		
		++top;
		stack[top] = value;

		printf("\nAfter push,the stack content is (top->bottom): \n");
		for (i = top; i >= 0; --i)
		{
			printf("%d ", stack[i]);
		}
		printf("\n");
	}
}

/* 出栈 */
int pop()
{
	int temp;
	int i;
	if (top < 0)
	{
		printf("\nThe stack is empty!\n");
		return -1;
	}
	printf("\nBefore pop, the stack content is (top->bottom): \n");
	for (i = top; i >= 0; --i)
	{
		printf("%d ", stack[i]);
	}

	temp = stack[top];
	--top;

	printf("\nThe pop value is [ %d ].\n", temp);
	printf("After pop, the stack content is (top->bottom):\n");
	if (top <0)
	{
		printf("It is empty.\n");
	}
	else {
		for (i = top; i >= 0; --i)
		{
			printf("%d ", stack[i]);
		}
	}
	
	printf("\n");
	return temp;
}

int main()
{
	int select;
	int stack[5];
	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("Please input the digit: ");
			scanf("%d", &value);
			push(value); /* 入栈 */
			break;
		case 2:
			value = pop(); /* 出栈 */
			break;
		default:
			printf("Please input the right choice !\n");
			break;
		}
		printf("\n(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);
	} while (select != 3);

	return 0;
}

运行结果如下图所示:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值