您的位置:首页 > 理论基础 > 数据结构算法

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

2016-10-28 21:57 344 查看
以下是“使用数组实现栈”的简单示例:

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


运行结果如下图所示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构