CoinBulb

Sunday, October 27, 2019

Singlly linked list.insert at start.insert at mid,insert at end

Singlly linked list 
insert at start 
insert at mid
insert at end
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;

};
class list
{
node *head;
node *tail;
public:
list()
{
head=NULL;
tail=NULL;
}
void insertatend(int value)
{
node *n=new node;
n->data=value;
n->next=NULL;
if(head==NULL)
{
head=n;
tail=n;

}
else
{
tail->next=n;
tail=n;
}
}
void display()
{
if(head==NULL)
{
cout<<"empty"<<endl;
}
else
{

node *temp=head;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
}
void insertatstart(int value)
{
node *n=new node;
n->data=value;
if(head==NULL)
{
head=n;
tail=n;
}
else
{
n->next=head;
head=n;
}
}
void insertatmid(int value)
{
node *n=new node;
n->data=value;
if(head==NULL)
{
head=n;
tail=n;

}
else
{
node *slow=head;
node *fast=head;
while(fast!=tail && fast->next!=tail)
{
fast=fast->next->next;
slow =slow->next;
}
n->next=slow->next;
slow->next=n;
}
}
};
int main()
{
list l;
l.insertatend(12);
l.insertatend(43);
l.insertatend(65);
l.insertatstart(136);
l.insertatstart(13);
l.insertatmid(17);
l.display();
}

No comments:

Post a Comment