2014-10-20 146 views
0

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

为什么下面的代码显示垃圾而不是项目?堆栈完全推下一个项目后,它会无限?还有其他方法可以使用数组来实现堆栈。但我想试试这个。

我们怎么能不使用指针来实现堆栈?

#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

!C = C++ ..都是不同的语言 – Haris 2014-10-20 17:08:14

+2

你真的没有一个“数据结构”在这里,只是一些变数。如果你正在学习C++,你想从一个'class'开始。而且,C和C++可以与最新标准大不相同。一般来说,你不应该跨标签。 – crashmstr 2014-10-20 17:08:49

+1

为什么不让你的堆栈成为一个类,所以逻辑与I/O是分开的,因此更容易停止问题。 – 2014-10-20 17:08:56

回答

1

其实你从来没有推元素到您的stack

将您的push代码更改为此。

if (top < (size -1)) { 
      ++top; 
      s[top] = item; 
     } 
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; 
+0

你应该真的解释_why_,为了帮助... – 2014-10-20 17:13:56

+1

@LightnessRacesinOrbit你是对的!它没有帮助 – 2014-10-20 17:25:30

+0

它不起作用 – 2014-10-20 17:25:45

1

我认为这个问题是在你第一次if声明。您应该分配给items[top]top(那是因为你必须存储在item阵列s[]):

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

仍然是同样的问题。 – 2014-10-20 17:23:39

+2

我刚才测试了代码。推/流行/显示工作正常。你确定你仍然在输出垃圾吗? – Seprum 2014-10-20 17:28:27