Aarav
Aarav

Reputation: 23

How to print linked list using c++ recursion in object oriented form (OOP)

i m just creating my on stack using linked list,but when i print elements using recursion it exit with random code in geany.

#include <iostream>
using namespace std;
class Node
{
    public:
    int data;
    Node* next;
};
class Stack
{
    public:
    Node* Top;
    void stack()
    {
        Top = NULL;
    }
    void pop()
    {
        if(Top == NULL)
        {
            cout<<"\nstack empty";
        }
        Top = Top->next;
    }
    
    void push(int data)
    {
        Node* newNode = new Node();
        newNode->data = data;
        newNode->next = Top;
        Top = newNode;
    }
    
    bool isEmpty()
    {
        if(Top == NULL)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    void print()
    {
        tem_print(Top);
    }
    
    void tem_print(Node* t_top)
    {
        if(t_top == NULL)
        {
            return;
        }
        tem_print(t_top->next);
        cout<<t_top->data;
    }
};
int main()
{
    Stack s;
    s.push(1);
    s.push(2);
    s.print();
    return 0;
}

i used a print() function inside it i called another temp print function which is used to print elements,It works fine if i used iteration method to print

output: freeze of 3sec

and prints this


(program exited with code: -1073741819)

Press any key to continue . . .

Upvotes: 1

Views: 117

Answers (2)

CiaPan
CiaPan

Reputation: 9570

Your pop function performs Top = Top->next; even if Top == NULL.

Upvotes: 1

cigien
cigien

Reputation: 60430

You are not initializing Top in your code, so the first time you read from it, you are invoking undefined behavior (UB). The result of a program with UB could be anything, including freezing for some time, or exiting with an error code.

This function:

void stack()
    {
        Top = NULL;
    }

looks suspiciously like a constructor. If so, you need to write:

Stack()
    {
        Top = NULL;
    }

or even better:

Stack() : Top(NULL) {}

In fact, you don't even need a constructor if you just initialize Top when you declare it inside the class.


Also, in your pop function, you are accessing next even if Top is NULL. Instead, you need an else statement:

void pop()
    {
        if(Top == NULL)
        {
            cout<<"\nstack empty";
        }
        else   // needed to avoid UB
            Top = Top->next;
    }

Here's a demo.


Also, you should avoid using NULL in your code: use nullptr instead. Finally, please avoid using using namespace std;, it's a bad habit.

Upvotes: 3

Related Questions