Assume that the following doubly linked list has been created with 5 nodes.

Question

Assume that the following doubly linked list has been created with 5 nodes. Fill the nodes with the last five digits of your roll number in sorted order. Write appropriate addresses of each node/pointer. The structure of the node is such that

 

Summary

For the first node, let the address be 100. For the second node let the address be 101. For the next three nodes let the addresses be 102,102 and 104 respectively.

 

Explanation

As mentioned in the summary, the addresses of the created with 5 nodes are 100,101,102,103, and 105 respectively.

 

Step 1:

For the first node, the address of the previous node is set to zero since there is no other node before the first node and the address of the next node is set to 101.

prev=NULL

next=101

 

Step 2:

For the second node, the address of the previous node is set to 100 since the address of the first node is100, and the address of the next node is set to 102.

prev=100

next=102

 

Step 3:

For the third node, the address of the previous node is set to 101, and the address of the next node is set to 103.

prev=101

next=103

 

Step 4:

For the fourth node, the address of the previous node is set to 102, and the address of the next node is set to 104.

prev=102

next=104

 

Step 5:

For the fifth node, the address of the previous node is set to 103, and the address of the next node is set to NULL since this is the last node and there is no other node present after this.

prev=103

next=NULL

 

Code:

In the given code, we create new nodes and initialize the given data step by step. Later we print out the whole link list.

#include<iostream>
using namespace std;
//Defining a class node
class Node
{
    public:
    	//Declaring members of the class node
    int data;
    //prev to indicate the previous node of the current node
    Node* prev;
    //next to indicate the next node of the current node
    Node* next;
};
void push(Node** head, int data)
{
    //Creating a new node
    Node* no= new Node();
    Node* pres = *head;
 
    //Initialize data
    no->data = data;
    no->next = NULL;
    //If linked list is empty
    if (*head== NULL)
    {
    	//Make the new node as head
        no->prev = NULL;
        *head= no;
        return;
    }
    //Otherwise, go to the last node
    while (pres->next != NULL)
        pres = pres->next;
    pres->next = no;
    n->prev = pres;
    return;
}
void print(Node* pres)
{
    cout<<"\nPrinting linked list\n";
    while (pres!= NULL)
    {
        cout<<" "<<pres->data<<" ";
        curr = pres->next;
    }
}
int main(){
    //Declaring head node
    Node* head=NULL;
    push(&head,1);
    push(&head,2);
    push(&head,3);
    push(&head,4);
    push(&head,5);
    print(head);
}

Output:

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *