Solved programming problem

Insert a New Node in Nth Position in Single Linked List in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

node *head=NULL;

void insert_node()

{

    node *temp=new node();

    node *last;

    cout<<"Data: ";

    cin>>temp->data;

    temp->next = NULL;

    if(head==NULL)

    {

        head=temp;

    }

    else

    {

        last = head;

        while(last->next != NULL)

        {

            last = last->next;

        }

        last->next = temp;

    }

}

void print_node()

{

    node *temp=head;

    while(temp!= NULL)

    {

        cout<< temp->data << " ";

        temp=temp->next;

    }

}

void add_node(int n,int data)

{

    node *temp=new node();

    node *last=head,*t;

    int count=1;

    temp->data= data; ///save data

    while(count<n-1)

    {

        last=last->next;

        count++;

    }

    t = last->next; ///save the nth position to anther node

    last->next =temp;

    temp->next = t; ///Linked new data to the previous nth position node

}

int main()

{

    int flag,n,data;

    do

    {

        cout<<"Press 1 to insert Node: ";

        cin>>flag;

        if(flag!=1) break;

        insert_node();

    }

    while(flag==1);

    cout<<"Your Linked List: "<<endl;

    print_node();

    cout<<"
 Enter The Position Where You want to Insert Node: ";

    cin>>n;

    cout<<"Data: ";

    cin>>data;

    add_node(n,data);

    cout<<"
Your Linked List: ";

    print_node();

    cout<<endl;

    return 0;

}

Output

Press 1 to insert Node: 1
Data: 1
Press 1 to insert Node: 1
Data: 2
Press 1 to insert Node: 1
Data: 3
Press 1 to insert Node: 1
Data: 4
Press 1 to insert Node: 1
Data: 5
Press 1 to insert Node: 0
Your Linked List:
1 2 3 4 5

Join the discussion

Add your comment