Home > Enterprise >  After inserting at head in linked list. Now what is name of that node which was head before insertin
After inserting at head in linked list. Now what is name of that node which was head before insertin

Time:05-05

// 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'?

CodePudding user response:

[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';
  • Related