Answer to Question #284835 in C++ for Tatheer

Question #284835

Print the doubly linked list in recursive order.

1
Expert's answer
2022-01-06T08:52:11-0500
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Node{
    public:
    int data;
    Node *next, *prev;
    Node();
    Node(int);
};
Node::Node(){
    next = NULL;
    prev = NULL;
}
Node::Node(int data){
    this->data = data;
    next = NULL;
    prev = NULL;
}
class DoublyLinkedList{
    Node *head, *tail;
    int size;


    public:
    DoublyLinkedList();
    void insert(int);
    void printRecursive(Node* c = NULL, Node* b = NULL);
};
DoublyLinkedList::DoublyLinkedList(){
    head = NULL;
    tail = NULL;
    size = 0;
}
void DoublyLinkedList::insert(int data){
    if(head == NULL){
        head = new Node(data);
        tail = head;
        size++;
    }
    else{
        tail->next = new Node(data);
        tail->next->prev = tail;
        tail = tail->next;
        size++;
    }
}


void DoublyLinkedList::printRecursive(Node* curr, Node* b){
    if(curr == NULL){
        curr = head;
    }
    if(curr == b){
        cout<<"\n";
        return;
    }
    if(curr != NULL){
        cout<<curr->data<<" ";
    }
    if(b == NULL){
        b = head;
    }
    printRecursive(curr->next, b);
}


int main(){
    DoublyLinkedList list;
    for(int i = 1; i <= 10; i++){
        list.insert(i);
    }
    list.printRecursive();
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog