📄 为堆栈数据的存取(使用数组.txt
字号:
/*堆栈 实验 堆栈数据的存取(使用数组) */
/*===============================================*/
/*程序构思: */
/*数据输入时,控制堆栈指针+1,若堆栈未满,则将数据存入堆栈中; */
/*数据输出时,若堆栈未空,则从堆栈中取出数据,并控制堆栈指针-1。*/
/*===============================================*/
/*程序源代码 */
/*==============Program Description==============*/
/*程序名称: stack01.c */
/*程序目的: 堆栈数据之存取(使用数组) */
/*程序提供: 马春江 */
/*===============================================*/
#include <stdlib.h>
#define MaxSize 10
int stack [MaxSize]; /*声明堆栈数组 */
int top=-1 /*堆栈顶端 */
/*===============================================*/
/*存入堆栈数据 */
/*===============================================*/
void push (int value)
{
int i;
if (top>=MaxSize) /*判断是否已超出堆栈最大容量*/
printf ("\n The stack is full !!\n);
else
{
printf ("\n The stack content before (top->bottom):");
for (i=top; i>=0; i--)
printf ("[%d]",stack[i]);
top++; /*堆栈顶端指针+1*/
stack[top]=value; /*将数据存入堆栈中*/
printf (\n The stack content after push (top->bottom):");
for (i=top; i>=0; i--)
printf ("[%d]", stack[i]);
printf (\n");
}
}
/*===============================================*/
/*从堆栈中取出数据 */
/*===============================================*/
int pop( )
{
int temp; /*暂存从堆栈取出来的数据*/
int i;
if (top<0) /*判断堆栈是否为空*/
{
printf ("\n The stack is empty!! \n");
return -1;
}
printf ("\n The stack content before (top->bottom):");
for (i=top; i>=0; i--)
printf ("[%d]", stack[i]);
temp=stack[top]; /*将取出数据暂存于变更中*/
top--; /*堆栈顶端指针-1*/
printf ("\n The pop value is [%d]",temp);
for (i=top; i>=0; i--)
printf ("[%d]", stack[i]);
printf ("\n");
return temp;
}
/*===============================================*/
/*主程序:可输入输出堆栈数据,并输出堆栈内容 */
/*===============================================*/
void main()
{
int select; /*选择功能变量 */
int stack[5]; /*堆栈数组 */
int i, value;
printf ("\n(1) Input a stack data");
printf ("\n(2) Output a stack data");
printf ("\n(3) Exit");
printf ("\n(1) Please select one=>");
scanf ("%d",&select);
do
{
switch (select) /*判断选择的功能 */
{
case 1: printf ("\n Please input the data=>");
scanf ("%d", &value);
push (value); /*将Value存入堆栈 */
break;
case 2: value=pop( ); /*从堆栈取出一元素存入Value*/
break;
}
printf ("\n (1) Input a stack data");
printf ("\n (2) Output a stack data");
printf ("\n (3) Exit");
printf ("\n Please select one=>");
scanf ("%d",&select);
printf ("\n");
} while (select !=3);
}
/*希望的结果 */
/*(1) Input a stack data */
/*(2) Output a stack data */
/*(3) Exit */
/*Please select one=>1 */
/*Please input the data=>4 */
/* */
/*The stack content before (top->bottom): [3] [2] [1] */
/*The stack content after push (top->bottom): [4] [3] [2] [1]*/
/* */
/*(1) Input a stack data */
/*(2) Output a stack data */
/*(3) Exit */
/*Please select one=>2 */
/*The stack content before (top->bottom): [4] [3] [2] [1] */
/*The pop value is [4] */
/*The stack content after pop (top->bottom): [3] [2] [1] */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -