
各位程序员们这个怎么做呀😭大一新生不会做程序题,里面的内容不会做,没有头绪,希望能够得到帮助,
基于Monster 组和GPT的调写:
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 栈的最大容量
int stack[MAXSIZE]; // 栈的数组
int top = -1; // 栈顶指针
// 进栈函数
void push(int x)
{
if (top == MAXSIZE - 1)
{
cout << "Stack overflow!" << endl;
return;
}
stack[++top] = x;
}
// 出栈函数
int pop()
{
if (top == -1)
{
cout << "Stack underflow!" << endl;
return -1;
}
return stack[top--];
}
// 输出中数据元素函数
void display()
{
if (top == -1)
{
cout << "Stack is empty!" << endl;
return;
}
cout << "Stack elements: ";
for (int i = top; i >= 0; i--)
{
cout << stack[i] << " ";
}
cout << endl;
}
int main()
{
int x;
// 调用进栈函数建立一个栈
for (int i = 1; i <= 5; i++)
{
push(i * 10);
}
// 读取栈顶元素
if (top == -1)
{
cout << "Stack is empty!" << endl;
}
else
{
cout << "Stack top element: " << stack[top] << endl;
}
// 从栈中删除数据元素
x = pop();
cout << "Popped element: " << x << endl;
// 输出栈中所有数据元素
display();
return 0;
}