How to create a pointer to another pointer in a linked list?

  

#include <iostream>

using namespace std;

  

class Node {

  

public:

    int data;

    Node* next;

  

    

    Node(int data)

    {

        this->data = data;

        this->next = NULL;

    }

  

    

    ~Node()

    {

        int value = this->data;

        if (this->next != NULL) {

            delete next;

            this->next = NULL;

        }

    }

};

  

void insertAtTail(Node*& tail, int d)

{

  

    

    Node* temp = new Node(d);

    tail->next = temp;

    tail = temp;

}

  

void print(Node*& head)

{

    Node* temp = head;

  

    while (temp != NULL) {

        cout << temp->data << " ";

        temp = temp->next;

    }

    cout << endl;

}

  

Node* createPointer(Node*& head)

{

  

    Node* dummy = new Node(-1);

  

    dummy->next = head;

  

    return dummy;

}

  

int main()

{

  

    

    

    Node* node = new Node(1);

  

    

    Node* head = node;

    Node* tail = node;

  

    insertAtTail(tail, 2);

    insertAtTail(tail, 3);

    insertAtTail(tail, 4);

    insertAtTail(tail, 5);

  

    cout << "Linked List: " << endl;

  

    print(head);

  

    Node* pt = createPointer(head);

  

    cout

        << "Dummy pointer pointing to head of Linked List: "

        << endl;

  

    print(pt);

  

    return 0;

}

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: