其实我想用简单的结构实现堆栈。简单堆栈实现
为什么下面的代码显示垃圾而不是项目?堆栈完全推下一个项目后,它会无限?还有其他方法可以使用数组来实现堆栈。但我想试试这个。
我们怎么能不使用指针来实现堆栈?
#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;
}
!C = C++ ..都是不同的语言 – Haris 2014-10-20 17:08:14
你真的没有一个“数据结构”在这里,只是一些变数。如果你正在学习C++,你想从一个'class'开始。而且,C和C++可以与最新标准大不相同。一般来说,你不应该跨标签。 – crashmstr 2014-10-20 17:08:49
为什么不让你的堆栈成为一个类,所以逻辑与I/O是分开的,因此更容易停止问题。 – 2014-10-20 17:08:56