#include <iostream>
using namespace std;
/*Stack
last in first out algorithm
pop, push, print*/
class Node{
private:
int a;
public:
Node *next;
Node(){
next = NULL;
};
Node(int b){
int a = b;
next = NULL;
}
int getValue();
};
int Node::getValue(){
return a;
}
class Stack{
Node *top;
public:
Node* pop();
void push(int);
Stack(){
top=NULL;
}
void printStack();
}aStack;
//pushing onto the stack
void Stack::push(int z){
//if top is not null create a temp link it to top then set point top to temp
if (top != NULL){
Node*temp = new Node(z);
temp->next = top;
top = temp;
}
else
//else just set the new node as top;
top = new Node(z);
top->next = NULL;
}
Node* Stack::pop(){
if (top == NULL){
cout << "Stack is empty" << endl;
}
else
//top = top->next;
return top;
//top = top->next;
}
//prints the stack
void Stack::printStack(){
int count = 0;
while(top!=NULL){
count++;
cout << count << ": " << (*top).getValue() << endl;
top = top->next;
}
}
int main(){
aStack.push(5);
aStack.printStack();
//cout << aStack.pop()->getValue()<< endl;
cin.get();
}
嘿傢伙,我正在審查我的數據結構。我無法弄清楚爲什麼在將空的堆棧上的數字5推出並打印出來後,我得到的輸出是0。請給我一個提示我做錯了,謝謝。C++堆棧實現意外輸出
與你的問題沒有關係,但有兩個註釋:1.'pop'應該刪除頂部。使用temp變量保存top並將top移動到next,然後返回temp。 2.'printStack'不應該改變'top',再次使用temp變量來迭代堆棧。 – SHR
感謝您的提示,我做了這些改變。 –