Regarding tail pointer

how can we maintain the tail pointer so that we can insert last node directly from tail pls tell me that code

Hey @ssmit_joshi
Just like you mantain head pointer ,in the same way mantain tail pointer.

void insert(node* &head ,node*&tail,int data){
    if(head==NULL){
        head=new node(data);
        tail=head;
        return;
    }
    tail->next=new node(data);
    tail=tail->next;
    return;
}

but then also we have to traverse through other nodes to insert at last ,without traversing with the help of tail pointer how can we add can u tell me

/hey @ssmit_joshi
above insertion is O(1) for one element at a time
Otherwise earlier version was O(length) for one elemenet at a time.

wt i m telling that if we want to add the number at last then how can we do without traversing other nodes, if we maintain a pointer that points to last then we can easily do insertion at last with help of that pointer so that how can we do ?

SO BRO ABOVE CODE IS FPR THAT ONLY ,it will insert the element at last without traversing the whole list.

yes i have understand these but one more thing firstly i m not creating any node directiy and then u insert not like that , i am doing like insert first ,insert in middle ,insert in last so if we want to maintain tail pointer in all these 3 then how can we do ?

for insert first only head node is required
for insert last only tail is reqd (above code)
for middle,u have to traverse the list there is no shortcut :slight_smile:

suggest me in this code i have sent to u how to maintain tail pointer first,last,middle

No changes in random assuming that element is not inserted at first or last position in it

can u tell me the error it is either printing first element or last element both together are not showing so pls help

Hey @ssmit_joshi
Can you please give me some custom input with expected output

in inser first 10 and in insert last 20 , so expected output to be 10,20

Here did 2 changes : https://ide.codingblocks.com/s/363063
Mentioned the changes in comments
If this resolves your query then please mark it as resolved :slight_smile:

thnks for the help …

1 Like

here insert at specific position output is not coming

and yaa i havedone temp u head also but whatever i am inserting it is inserted last only not at the specific position