TheFestFever.com

Our aim is to connect students from campuses all over Delhi by making them aware of all Technical, Cultural, Management fests, workshops, Seminars organized by every college in Delhi.

Join Us Now

Program 40: Write a C++ program to insert a new node at the middle of singly linked list.

#include<iostream>
using namespace std;

class node
{
	public:
		int data;
		node *next;
		node(int val=0,node *ptr=0)
		{
			data=val;
			next=ptr;
		}
};

class singly
{
	node *head=new node(0),*tail=new node(0);
	public:
		singly(node *h=0,node *t=0)
		{
			head=h;
			tail=t;
		}
		void add_at_value(int val)
		{
			node *n1=new node(val);
			if(head==0)
			{
				head=n1;
				tail=n1;
			}
			else
			{
				tail->next=n1;
				tail=n1;
			}
		}
		void add_at_middle(int val,int pos)
		{
			node *n1=new node(val);
			node *temp=head;
			for(int i=1;i<pos-1;i++)
			temp=temp->next;
			n1->next=temp->next;
			temp->next=n1;
		}
		void display()
		{
			node *temp=head;
			while(temp!=0)
			{
				cout<<"\n"<<temp->data;
				temp=temp->next;
			}
		}
};

int main()
{
	int pos,num,val;
	cout<<"\nenter the number of node : ";
	cin>>num;
	singly s;

	for(int i=0;i<num;i++)
	{
		cout<<"\ninput data for node "<<i+1<<" : ";
		cin>>val;
		s.add_at_value(val);
	}

	cout<<"\ndata entered in list : ";
	s.display();
	cout<<"\nenter the position to insert new node : ";
	cin>>pos;
	cout<<"\ninput data for node : ";
	cin>>val;

	s.add_at_middle(val,pos);
	cout<<"\nnew linked list : ";
	s.display();	
	return 0;
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.