Why it's printint position doesn't exist everytime and also it's not printing the 3rd data?

0 votes
asked Oct 4, 2018 by Amey Bikram (120 points)
#include <iostream>

using namespace std;

struct dllnode
{
    int data;
    dllnode *next,*prev;
};
class dlinked_list
{
    dllnode *head,*tail;
public:
    dlinked_list()
    {
        head=NULL;
        tail=NULL;
    }
    void insertionindll(int ,int);
    static void display(dllnode *);
    dllnode* gethead()
    {
        return head;
    }
    dllnode* create_node(int data);
};
dllnode* dlinked_list::create_node(int n)
{
    dllnode *temp=new dllnode;
    temp->data=n;
    temp->prev=NULL;
    temp->next=NULL;
    return temp;
}
void dlinked_list::insertionindll(int n, int pos)
{
    dllnode *temp;
    int k=1;
    dllnode *newnode= create_node(n);
    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)
            head->prev=newnode;
        head=newnode;
        return;
    }
    temp=head;
    //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++;
        temp=temp->next;
    }
    if(k!=pos)
    {
        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)
{
    dllnode *ptr;
    ptr=a;
    while(ptr->next!=NULL)
    {
        cout<<ptr->data<<endl;
        ptr=ptr->next;
    }
    return;
}
int main()
{
    /* code */
    dlinked_list a;
    a.insertionindll(1,1);
    a.insertionindll(2,2);
    a.insertionindll(3,3);
    dlinked_list::display(a.gethead());
    return 0;
}

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...