Singly linked list

<br />#include<conio.h>
#include<iostream>
using namespace std;
int num;
struct node
{
int data;
node *link;
}*head,*ptr,*nptr,*sptr;

void create_node()
{
if(head==NULL)
{
nptr=new node;
cout<<"Create First node:"<<" ";
cin>>num;
nptr->data=num;
nptr->link=NULL;
head=nptr;
}
}

void display()
{
ptr=head;
cout<<endl<<"Linked list is:"<<endl;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->link;
}
cout<<endl;
}

void insert_beg()
{
nptr=new node;
cout<<endl<<"Enter a data to be inserted at beg:"<<" ";
cin>>num;
nptr->data=num;
ptr=head;
nptr->link=ptr;
head=nptr;
}

void insert_last()
{
cout<<endl<<"Enter a data to be inserted at last:"<<" ";
cin>>num;
ptr=head;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
nptr=new node;
nptr->data=num;
nptr->link=NULL;
ptr->link=nptr;
}

void insert_pos()
{
int anum;
cout<<endl<<"Enter a data to be inserted:"<<" ";
cin>>num;
cout<<endl<<"After which data:"<<" ";
cin>>anum;
nptr=new node;
nptr->data=num;
ptr=head;
while(ptr!=NULL && ptr->data!=anum)
{
ptr=ptr->link;
}
nptr->link=ptr->link;
ptr->link=nptr;
}
//--------------------------------------------------------
void deletel()
{
ptr=head;
cout<<endl<<"Enter element to be deleted:"<<" ";
cin>>num;
while(ptr!=NULL)
{
if(ptr->data==num)
{
if(ptr==head)
{
sptr=head;
head=head->link;
delete sptr;
break;
}
else
{
sptr->link=ptr->link;
delete ptr;break;
}
}
else
{
sptr=ptr;
ptr= ptr->link;
}
}
}
//--------------------------------------------------------
int main()
{
create_node();
int ch=0;
do{
cout<<endl<<"1. Enter at the first position:"<<endl;
cout<<"2. Enter at the middle:"<<endl;
cout<<"3. Enter at the Last:"<<endl;
cout<<"4. Delete:"<<endl;
cout<<"5. Display:"<<endl;
cout<<"6. Exit:"<<endl;
cout<<"Enter your Choice:-"<<" ";
cin>>ch;
switch(ch)
{
case 1:
insert_beg();
break;
case 2:
insert_pos();
break;
case 3:
insert_last();
break;
case 4:
deletel();
break;
case 5:
display();
break;
}
}
while(ch!=6);
cout<<endl<<"Bye...!! @Myprogworld";
getch();
return 0;
}

Singly linked list

Leave a comment