Home > front end >  How to insert a new node at any given position in linked list?
How to insert a new node at any given position in linked list?

Time:07-30

Kindly check my code below. I am not getting the actual output when I run this program.

What I want to do is to insert a new node at the position entered by the user. I have tested this code by entering 5 values for 5 nodes i.e 1,2,3,4,5 and then I entered position 2 to insert a value 8, but when I display it, it gives all other values except the value that I entered at the specific position.

#include<iostream>
using namespace std;

class Node
{
    public:
        int data;
        Node* next;
};

int main()
{
    int choice, pos, count = 0, i = 1;
    Node* head, *newnode, *temp;
    head = 0;

    do
    {
        count  ;
        newnode=new Node();
        cout<<"Enter data:";
        cin>>newnode->data;
        newnode->next=0;
        if(head==0)
            head=temp=newnode;
        else 
        {
            temp->next=newnode;
            temp=newnode;
        }
        cout<<"Do you want to create a new node... press 0 for no and 1 yes:";
        cin>>choice;
    }while(choice==1);

    cout<<"Enter position:";
    cin>>pos;
    if(pos>count)
    {
        cout<<"Invalid position\n";
    }
    else 
    {
        temp=head;
        while(i<pos)
        {
            temp=temp->next;
            i  ;
        }
        cout<<"Enter data you want to insert:";
        newnode=new Node();
        cin>>newnode->data;
        newnode=temp->next;
        temp->next=newnode; 
    }

    temp=head;

    while(temp!=0)
    {
        cout<<temp->data;
        temp=temp->next;
    }
}

CodePudding user response:

Your problem is here:

cout<<"Enter data you want to insert:";
newnode=new Node();
cin>>newnode->data;
newnode=temp->next;
temp->next=newnode;

newnode=temp->next makes newnode equal to 0, then temp->next=newnode makes temp->next equal to zero.

Perhaps you meant to write newnode->next = temp->next instead?

  • Related