#include struct node { node *next = { nullptr }; node *prev = { nullptr }; int value; node(int i=0) { value = i; } }; static void print_list(node *phead, node *ptail) { std::cout << "************ list **************" << std::endl; std::cout << "head: " << phead << std::endl; std::cout << "tail: " << ptail << std::endl; while(phead) { std::cout << "node: " << phead << std::endl; // print the address of the node std::cout << " next=" << phead->next << std::endl; std::cout << " prev=" << phead->prev << std::endl; std::cout << " value=" << phead->value << std::endl; phead = phead->next; // prepare to print the 'next' node } } int main() { node *phead = nullptr; node *ptail = nullptr; print_list(phead, ptail); // insert a new node into an empty list node *pn1 = new node(1); phead = pn1; // the new node is both the head ptail = pn1; // ...and tail node print_list(phead, ptail); // insert a new node at the head of a non-empty list node *pn2 = new node(2); pn2->next = phead; // link the new node to node #1 phead->prev = pn2; // link from the prior head node #1 back to this new one phead = pn2; // the new node #2 is the new head of the list print_list(phead, ptail); // insert a new node at the tail of a non-empty list node *pn3 = new node(3); pn3->prev = ptail; // point backwards to the previous tail node ptail->next = pn3; // link from the prior tail node #1 foreward to this new one ptail = pn3; print_list(phead, ptail); // insert a new node into the middle of the list after node #1 node *pn4 = new node(4); pn4->prev = pn1; // connect to new node to neighboring nodes pn4->next = pn1->next; pn4->prev->next = pn4; // connect neighbors to the new node pn4->next->prev = pn4; print_list(phead, ptail); return 0; } #if 0 // generic node insert logic: pn = new node(2); if (phead) { pn->next = phead; // link the new node to node #1 phead->prev = pn; // link from node #1 back to this new node #2 } else // list was empty! { ptail = pn; } phead = pn; // the new node #2 is the new head of the list #endif