gpt4 book ai didi

c++ - 简单的堆栈实现

转载 作者:行者123 更新时间:2023-11-28 00:23:09 25 4
gpt4 key购买 nike

其实我想用简单的结构来实现堆栈。

为什么下面的代码显示的是垃圾而不是项目?在堆栈满后插入下一个项目进入无穷大?还有其他方法可以使用数组实现堆栈。但我想试试这个。

我们如何在不使用指针的情况下实现堆栈?

#include <iostream>
#define size 5

using namespace std;

int main()
{
int s[size];
int top = -1,item,choice;
char ans;

do {
cout << " =======================";
cout << " \n|Implementation of Stack|\n";
cout << " =======================";
cout<<"\n MAIN NENUE";
cout<<"\n 1. Push \n 2. Pop \n 3.Display ";
cin>>choice;
switch (choice) {
case 1:
cout<<"\n Enter the Item to be Pushed ";
cin>>item;
if (top != size -1) {
top++;
top = item;
} else {
cout<<"\nStack is Full ";
}

break;
case 2:
if (top == -1) {
cout<<"\n Stack is Empty ";
} else {
int item;
item = s[top];
top--;
}
break;
case 3:
if (top == -1) {
cout<<"\n Stack is Empty ";
} else {
for (int i = top; i >= 0; i--) {
cout<<"|" << s[i] << "|"<<endl;
}
}

break;

default:
cout<<" \n You have Pressed Invalid Key";
break;
}

cout<<"\n Do You Want To Continue ";
cin>>ans;
} while (ans == 'Y' || ans=='y');

return item;
}

最佳答案

实际上,您永远不会将元素压入您的堆栈

将您的 push 代码更改为此。

if (top < (size -1)) {
++top;
s[top] = item;
}

关于c++ - 简单的堆栈实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26471086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com