1. 程式人生 > >資料結構示例之使用陣列實現棧

資料結構示例之使用陣列實現棧

以下是“使用陣列實現棧”的簡單示例:

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;
}

執行結果如下圖所示: