Solved programming problem

Find Nth node in a 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 *last= head;

    if(head==NULL)

    {

        cout<<"
No Data Found
";

        return;

    }

    while(last!=NULL)

    {

        cout<<last->data<<" ";

        last= last->next;

    }

}

void search_index(int n)

{

    node *temp=head;

    int count=1;

    while(count!=n) ///find the index

    {

        temp = temp->next;

        count++;

    }

    cout<<"
Value: "<<temp->data<<endl;

}

int main()

{

    int flag,n;

    do

    {

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

        cin>>flag;

        if(flag!=1)break;

        insert_node();

    }

    while(flag==1);

    cout<<"Your LInked List: ";

    print_node();

    cout<<"
Enter The Index You Want to Search: ";

    cin>>n;

    search_index(n);

    return 0;

}

Output

Press 1 to insert Node: 1
Data: 4
Press 1 to insert Node: 1
Data: 58
Press 1 to insert Node: 1
Data: 6
Press 1 to insert Node: 1
Data: 56
Press 1 to insert Node: 1
Data: 60
Press 1 to insert Node: 09
Your LInked List: 4 58 6 56 60
Enter The Index You Want to Search: 3

Value: 6

Join the discussion

Add your comment