Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

After inserting at head in linked list. Now what is name of that node which was head before inserting new node

// insert at head LL
#include<iostream>
using namespace std;
class node{
    public:
    int data;
    node* next;
    node(int val){
        data=val;
        next=NULL;
    }
};
void insertAtHead(node* &head, int value){
    node* n= new node(value);
    n->next=head;
    head=n;
}
void display(node* head){
    while(head!=NULL){
        cout<<head->data<<"->";
        head=head->next;
    }
    cout<<"NULL"<<endl;
}
int main(){
    node* head=new node(1);
    node* second=new node(2);
    node* third=new node(3);
    head->next=second;
    second->next=third;
    insertAtHead(head, 0);
    display(head);
    cout<<head->data; // accessing data of new head. 
    // how to access data of node which was previously head?
    return 0;
}

Now after inserting new node with data ‘0’ it’s our new head but node which was previously head node, how can we access it’s data and what is name of that node because it’s name is definitely not ‘n’?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[H]ow to access data of node which was previously head?

The previous head node is now the currents head-nodes next node:

std::cout << "Previous head value: " << head->next->data << '\n';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading