0% found this document useful (0 votes)
5 views

Insert Node

Uploaded by

Ajay Gangwar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Insert Node

Uploaded by

Ajay Gangwar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

// Singly linked list between

#include <iostream>
#include <string>
using namespace std;

struct node
{
string name;
int age;
node* next;
}*p,*h;

void input(struct node *p)


{
cout<<"Name:";
cin>>p->name;
cout<<"Age:";
cin>>p->age;
p->next=NULL;
}

void insertb(int n)
{
struct node *pos;
int i=1;
for(pos=h;pos->next!=NULL;pos=pos->next)
i++;
if(i<n)
{
cout<<"enter valid position"<<endl;
}
else
{
for(pos=h,i=1;(pos->next!=NULL && i<n-1);pos=pos->next,i++);
p=new node();
input(p);
p->next=pos->next;
pos->next=p;
}
}

int main()
{
struct node *pos;
int no,x;
cout<<"enter no of intial nodes to create"<<endl;
cin>>no;
h=new node();
input(h);
for(int i=2;i<=no;i++)
{
cout<<"Enter data to node no :"<<i<<endl;
p=new node();
input(p);
if(i==2)
h->next=p;
else
{
for(pos=h;pos->next!=NULL;pos=pos->next);
pos->next=p;
}
}
cout<<"\nLinked list"<<endl;
for(pos=h;pos!=NULL;pos=pos->next)
{
cout<<"-> "<<pos->name<<" "<<pos->age<<endl;
}

cout<<"enter the position to insert a node(between nodes)"<<endl;


cin>>x;
insertb(x);
for(pos=h;pos!=NULL;pos=pos->next)
{
cout<<"-> "<<pos->name<<" "<<pos->age<<endl;
}
}

You might also like