C语言实现在屏幕上输出栈中的元素和插入元素代码
时间: 2024-06-01 15:12:56 浏览: 10
可以使用下面的代码实现:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
int stack[MAXSIZE]; //定义栈
int top = -1; //定义指向栈顶元素的指针
//栈的插入操作
void push(int data)
{
if(top == MAXSIZE - 1) //栈满的情况
{
printf("Stack Overflow\n");
return;
}
stack[++top] = data; //将元素插入栈中
}
//栈的弹出操作
void pop()
{
if(top == -1) //栈空的情况
{
printf("Stack Underflow\n");
return;
}
printf("poped element is: %d\n", stack[top--]); //将栈顶元素弹出并输出
}
//输出栈中的元素
void display()
{
if(top == -1) //栈空的情况
{
printf("Stack is empty\n");
return;
}
printf("Elements in the stack are:\n");
for(int i = top; i >= 0; i--)
{
printf("%d\n", stack[i]); //从栈顶开始输出栈中所有元素
}
}
int main()
{
int choice, data;
while(1) //循环等待用户输入操作
{
printf("Please enter your choice:\n");
printf("1. Push element\n");
printf("2. Pop element\n");
printf("3. Display elements\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch(choice) //根据用户的选择执行相应的操作
{
case 1:
printf("Please enter the element to be pushed: ");
scanf("%d", &data);
push(data);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
break;
}
}
return 0;
}
希望这能回答您的问题。
相关推荐
![torrent](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)