Doubly Linked List Creation and Insertion At Beg, mid, and at end C++
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next, *prev;
};
struct node *head, *tail, *newnode, *temp;
int count=0;
void create()
{
int choice=1;
while(choice==1){
::count++;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->next=0;
newnode->prev=0;
cout<<"\nenter data: ";
cin>>newnode->data;
if(head==0)
{
head=newnode;
tail=newnode;
}
else
{
newnode->prev=tail;
tail->next=newnode;
tail=newnode;
}
cout<<"Want another element to be inserted(0,1): ";
cin>>choice;
}
}
void insertbeg()
{
int choice = 1;
while(choice==1){
::count++;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->next=0;
newnode->prev=0;
cout<<"enter data: ";
cin>>newnode->data;
//first make the link to the previously existing first node;
head->prev=newnode;
newnode->next=head;
head=newnode;
cout<<"Want another element to be inserted in beginning(0,1): ";
cin>>choice;
}
}
void insertend()
{ int choice =1;
while(choice==1){
::count++;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->next=0;
newnode->prev=0;
cout<<"enter data: ";
cin>>newnode->data;
tail->next=newnode;
newnode->prev=tail;
tail=newnode;
cout<<"Want another element to be inserted at end(0,1): ";
cin>>choice;
}
}
void insertpos()
{
int choice = 1,pos,i;
while(choice==1)
{
cout<<"enter the position of insertion greater than 1 and less than the length of list(0,1): ";
cin>>pos;
if(pos>1 && pos<::count)
{
::count++;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->next=0;
newnode->prev=0;
cout<<"enter data: ";
cin>>newnode->data;
// Forming link;
temp=head; i=1;
while(i<pos-1)
{
temp=temp->next;
i++;
}
newnode->prev=temp;
newnode->next=temp->next;
temp->next->prev=newnode;
temp->next=newnode;
cout<<"\nDo you want another element to be inserted in middle (0,1): ";
cin>>choice;
}
else
{
cout<<"\nPosition cannot be <=1 or >=size of list\n";
cout<<"Do you want to insert again(0,1): ";
cin>>choice;
}
}
}
void listprint()
{
temp=head;
cout<<"size is: "<<::count<<endl;
while(temp!=0)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main()
{
int f=1, conti=1, choice;
while(conti==1)
{
cout<<"\npress 1. to create list";
cout<<"\npress 2. to enter node at beginning";
cout<<"\npress 3. to enter node at end";
cout<<"\npress 4. to enter node at certain position";
cout<<"\npress 5. to print list";
cout<<"\nenter your choice from given list: ";
cin>>choice;
if(choice==1)
{ if(f==1)
{create();
f=0;}
else
cout<<"list already created";
}
else if(choice==2)
insertbeg();
else if(choice==3)
insertend();
else if(choice==4)
insertpos();
else if(choice==5)
listprint();
else
cout<<"invalid choice";
cout<<"\nDo you want to continue(0,1): ";
cin>>conti;
}
}
This is the entire code for doubly linked list creation, insertion,
ReplyDeleteYou can directly copy entire code and run easily