C 堆栈实现意外输出

C++ Stack implementation unexpected output

本文关键字:输出 意外 实现 堆栈      更新时间:2023-10-16
#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。请给我一个提示我做错了什么,谢谢。

Node::Node中,您正在遮蔽成员变量a

int a = b;

替换
a = b;

或更高

Node(int b): a(b), next(NULL){}

我在您的代码中发现的一个问题是,您在节点的类中声明另一个a变量

Node(int b){
    //int a = b; when you define a new `a` variable, old one is ignored
    a=b;
    next = NULL;
}

所有私人成员均在类内定义,因此所有类都可以看到变量a。但是,当您在子范围内声明一个新变量时,在此子镜头内忽略了一般范围中的a变量