I am trying to insert a value at the end of a doubly linked list , I get successful in inserting the value at head or first node but the second value is not getting inserted
The issue here is while entering the second value
class d_list
{
private:
struct node
{
double data;
node *next;
node *previous;
};
node *first;
node *last ;
public:
d_list(void)
{
first = nullptr;
last = nullptr;
};
void append(double);
};
void d_list::append(double num)
{
node *ptr;
node *toinsert;
if(!first)
{
first = new node;
first->previous= nullptr;
first->data = num;
last= new node;
first->next= last->previous;
last->previous = first->next;
last->next= nullptr;
}
else
{
if(last->next == nullptr)
{
ptr = new node;
ptr->next =last->previous;
ptr->data=num;
last->previous = ptr->next ;
}
last->next= nullptr;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
d_list aa;
cout<<"going to append first"<<endl;
aa.append(44);
cout<<"going to append second"<<endl;
aa.append(50.5);
return 0;
}
You have a number of problems in your code:
nodenext and previous members are never initialized anywhere and as a result are undefined when used. Either add a constructor tonodeor ensure they are initialized after allocation.first->nextis left undefined and why are you creating two nodes, both first and last? In a list with one element thenfirst == last. The setting of next/previous in first/last doesn’t make any sense either.last->nextshould always be null, as shouldfirst->previous.I would suggest taking a step back from the code for a bit to ensure you properly understand the concepts behind a doubly-linked list. Draw out a list on paper with next/prev arrows and see how they need to be changed when adding nodes to an empty/non-empty list as well as how to delete and move nodes around. Once you figure out how next/prev should be set then translating that into code should be relatively straight forward.
Edit to answer comment:
To add a new node you can technically add it anywhere but it is usually added at the end (at least from what I’ve seen). See the other answers for a complete and correct code for adding new nodes in an empty and non-empty list.