C++ program for linked lists
Linked lists
A linked list is a linear data structure where each element is a separate object.


- Each node of a list is comprising of two items - the data and a reference to the next node. The last node has a reference to null.
- The entry point into a linked list is called the head of the list. It should be noted that head is not a separate node, but the reference to the first node. If the list is empty then the head is a null reference.
- A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow and shrink on demand.
- One disadvantage of a linked list against an array is that it does not allow direct access to the individual elements. If you want to access a particular item then you have to start at the head and follow the references until you get to that item.
Program:
#include<iostream>
using namespace std;
struct node{
int info ;
node *next ;
}*t;
node *head=NULL;
node *tail=NULL;
void add(int n)
{node *tmp=new node;
tmp->info=n;
tmp->next=NULL;
if(head ==NULL)
{head=tmp;
tail=tmp;
}
else {
tail->next=tmp;//tail changes its previous value to tmp
tail=tail->next;}
}
void beg(int n)
{node *tmp=new node;
tmp->info=n;
tmp->next=head;//Assigns next pointer of head to tmp
head=tmp;//assigns address of tmp to head
}
void end(int n) //insertion at end
{node *tmp=new node;
tmp->info=n;
tail->next=tmp;
tail=tmp;
}
void pos(node *a,int n) // insertion after a position
{node *tmp=new node;
tmp->info=n;
tmp->next=a->next;
a->next=tmp;
}
void display() //Display function
{ node *f=head;
while(f!=NULL)
{cout<<f->info<<"->";
f=f->next;}
cout<<"!!!";
}
void del() // Delete function
{
node *tmp=new node;
tmp=head;
head=head->next;//head becomes the next node
delete tmp;
}
main()
{int val,p,ch,val1;
char c;
node *t;
do{cout<<"Enter the info to create new node :";
cin>>val;
add(val);
cout<<"Want to add more : ";
cin>>c;
}while(c=='y'||c=='Y');
t=head;
cout<<"Enter your choice \n1.Beg \n2.After a node \n3.end \n4.Delete \nChoice:" ;
cin>>ch;
switch(ch)
{case 1:cout<<"Enter value you want to insert";
cin>>val1;
beg(val1);
break;
case 2:cout<<"Enter value you want to insert";
cin>>val1;
cout<<"Enter position you want to insert";
cin>>p;
for(int i=1;i<p;i++)
{
t=t->next;
}
pos(t,val1);
break;
case 3:cout<<"Enter value you want to insert";
cin>>val1;
end(val1);
break;
case 4:del();}
cout<<"Display ";
display();
}
Output of the program:
Output of the program:

Comments
Post a Comment