实际上我想以简单的结构实现堆栈。
为什么下面的代码显示垃圾而不是项目?堆栈完全推送下一个项目后它会变为无穷大?还有其他方法可以使用数组实现堆栈。但我想试试这个。
我们如何在不使用指针的情况下实现堆栈?
#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;
}
答案 0 :(得分:1)
而不是这些陈述
if (top != size -1) {
top++;
top = item;
写
if (top != size -1) {
s[++top] = item;
您可以为堆栈添加一些有用的功能。例如
int s[size];
int top = -1,item,choice;
char ans;
auto is_empty = [&top] { return top == -1; };
// ...
然后你可以写
case 3:
if ( is_empty() ) {
cout<<"\n Stack is Empty ";
} else {
for (int i = top; i >= 0; i--) {
cout<<"|" << s[i] << "|"<<endl;
}
}
break;
答案 1 :(得分:1)
我认为问题出在您的第一个if
声明中。您应该将item
分配给s[top]
,但不能分配给top
(因为您必须将item
存储在数组s[]
中):
if (top != size -1) {
top++;
s[top] = item;
}
答案 2 :(得分:1)
实际上,你从未将元素推入stack
。
将您的push
代码更改为此。
if (top < (size -1)) {
++top;
s[top] = item;
}