I am trying to implement a Stack using a Linked List in C++. When I run my code, nothing is outputted to the console, but it compiles without errors. The problem seems to come from my pointer for the top node. I initially made the top node without a pointer, but that created problems of its own when I tried to initialize it as NULL.
Code:
#include <iostream>
using namespace std;
class Stack{
class Node{
int data;
Node* prev;
public:
Node(int x){
data=x;
}
void set_prev(Node nd){
*prev=nd;
}
Node get_prev(){
return *prev;
}
int get_data(){
return data;
}
};
Node* top = NULL;
int count = 0;
public:
void push(int x){
Node new_node(x);
new_node.set_prev(*top);
*top = new_node;
count++;
cout << "Pushing" << endl;
}
void pop(){
if(!is_empty()){
int data = (*top).get_data();
*top = (*top).get_prev();
count--;
cout << "Popping" << endl;
}else{
cout << "Stack is empty." << endl;
}
}
int peek(){
return (*top).get_data();
}
int get_count(){
return count;
}
bool is_empty(){
return !count;
}
};
int main(){
Stack stk;
stk.push(5);
stk.push(13);
cout << stk.peek() << endl;
}