G V
G V

Reputation: 101

C++ Stack implementation unexpected output

#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();
}

Hey guys, I am reviewing my data structures. I am not able to figure out why i am getting output 0 after pushing the number 5 on the empty stack and printing it out. Please give me a HINT on what i am doing wrong, thanks.

Upvotes: 0

Views: 80

Answers (2)

Abozanona
Abozanona

Reputation: 2285

One problem I find in your code is thay you are declaring another a variable in the class of node

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

All private members are defined inside the class, so all the class can see the variable a. but when you declare a new variable in a sub-scope, the a variable in the general scope is ignored inside this sub-scope

Upvotes: 1

vsoftco
vsoftco

Reputation: 56547

In Node::Node you are shadowing the member variable a,

int a = b;

replace it by

a = b;

or better, use a constructor initializer list

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

Upvotes: 4

Related Questions