I'm practicing on insertion in doubly linked list. I don't know why this code isn't working properly. The output of this code is :
position doesn't exist
position doesn't exist
1
2
As you can see it's not even printing the 3rd data. I know I am doing something wrong but I'm not able to identify my mistake in this code. Plz help me out.
#include <iostream>
using namespace std;
struct dllnode
{
int data;
dllnode *next,*prev;
};
class dlinked_list
{
dllnode *head,*tail;
public:
dlinked_list() //Constructor
{
head=NULL;
tail=NULL;
}
void insertionindll(int ,int);
static void display(dllnode *);
dllnode* gethead()
{
return head; //returning head pointer of the linkedlist
}
dllnode* create_node(int data);
};
dllnode* dlinked_list::create_node(int n) //Creating a new node
{
dllnode *temp=new dllnode;
temp->data=n;
temp->prev=NULL;
temp->next=NULL;
return temp; //returning the address of the newly created node to line no. 39
}
void dlinked_list::insertionindll(int n, int pos)
{
dllnode *temp;
int k=1;
dllnode *newnode= create_node(n); //storing address of the newly created node
if(!newnode)
{
cout<<"Memory Error"; //Checking memory error
return;
}
newnode->data=n;
if(pos==1) //Insertion at the beginning//
{
newnode->next=head;
newnode->prev=NULL;
if(head) //checking if head!=NULL
head->prev=newnode;
head=newnode; //now head points to the newly created node
return;
}
temp=head; //temp is now pointing to the first node
//After this loop temp will either point to the last node
//or the previous node at which we want to insert newnode
while(k<pos && temp->next!=NULL)
{
k++; //incrementing k
temp=temp->next;
}
if(k!=pos) //checking if the position doesn't exist
{
cout<<"position doesn't exist"<<endl;
}
newnode->prev=temp;
newnode->next=temp->next;
if(temp->next)
temp->next->prev=newnode;
temp->next=newnode;
return;
}
void dlinked_list::display(dllnode *a) //for displaying the created linked list
{
dllnode *ptr; //declaring a pointer which points to the head of the linked list
ptr=a;
while(ptr->next!=NULL) //iterating untill the last node
{
cout<<ptr->data<<endl; //printing data of the linked list
ptr=ptr->next; //pointng to the next node
}
return;
}
int main()
{
/* code */
dlinked_list a; //creating an object a of class dlinked_list
a.insertionindll(1,1); //here insertionindll function is called
a.insertionindll(2,2);
a.insertionindll(3,3);
dlinked_list::display(a.gethead()); //display function is called by passing head pointer
return 0;
}