Insert node at beginning, in-between and end of the linked list

#include<iostream>
#include<stdlib.h>
using namespace std;

class node
{
int data;
node *next;
public:
node *create(node *);
void display(node *);
void insert_end(node*);
void insert_beg(node*);
void insert_in(node *);
};



node * node:: create(node *head)
{
head=new node;
head->next=NULL;
return head;
}

void node:: display(node *head)
{
node *curr;
curr=head->next;
while(curr!=NULL)
{
cout<<curr->data<<"->";
curr=curr->next;
}
}

void node::insert_end(node *head)
{
node *temp;
temp=new node;
cout<<"\nEnter data\n";
cin>>temp->data;
node *curr;
curr=head;
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=temp;
}

void node::insert_beg(node *head)
{
node *temp;
temp=new node;
cout<<"Enter data";
cin>>temp->data;
temp->next=NULL;
if(head->next==NULL)
{
cout<<"yes";
head->next=temp;
}
else
{
node *curr;
curr=head->next;
head->next=temp;
temp->next=curr;
}

}

void node::insert_in(node *head)
{
node *temp,*curr;
temp=new node;
cout<<"\nEnter temp data\n";
cin>>temp->data;
temp->next=NULL;
int value;
cout<<"\nEnter the value after you have to insert temp node\n";
cin>>value;
curr=head;
while(curr->data!=value)
{curr=curr->next;
}
temp->next=curr->next;
curr->next=temp;
}



int main()
{
node obj;
int ch;
while(1)
{
cout<<"\n1: Create"
"\n2: Display"
"\n3: Insert_end"
"\n4: Insert_beg"
"\n5: Insert_in"
"\n6: exit";
cout<<"\nEnter your choice\n";
cin>>ch;

switch(ch)
{
case 1: node *head;
head=obj.create(head);
break;
case 2:
obj.display(head);
break;
case 3:
obj.insert_end(head);
break;
case 4:
obj.insert_beg(head);
break;

case 5:
obj.insert_in(head);
break;

case 6:
exit(0);
}
}
}







Post a Comment

0 Comments