#include struct node { node *next; int value; }; /** * Print the addresses and values of each node starting with p. * * @param p The address of the first node in the list to print. ********************************************************************/ static void print_list(node *p) { std::cout << "************ list **************" << std::endl; while(p) { std::cout << "node: " << p << std::endl; // print the address of the node std::cout << " next=" << p->next << std::endl; std::cout << " value=" << p->value << std::endl; p = p->next; // prepare to print the 'next' node } } /** * Demonstrate linked list insertions. ********************************************************************/ int main() { node *phead = nullptr; // initialize the list to "empty" print_list(phead); std::cout << "*** insert a new node into an empty list" << std::endl; node *pn1 = new node(); pn1->value = 1; pn1->next = nullptr; phead = pn1; // the new node is the head print_list(phead); // 1 std::cout << "*** insert a new node at the head of a non-empty list" << std::endl; node *pn2 = new node(); pn2->value = 2; pn2->next = phead; // link the new node to node #1 phead = pn2; // the new node #2 is the new head of the list print_list(phead); // 2 -> 1 std::cout << "*** insert a new node at the tail of a non-empty list (after #1)" << std::endl; node *pn3 = new node(); pn3->value = 3; pn3->next = nullptr; pn1->next = pn3; // link from the prior tail node #1 foreward to this new one print_list(phead); // 2 -> 1 -> 3 std::cout << "*** insert a new node into the middle of the list after node #1" << std::endl; node *pn4 = new node(); pn4->value = 4; pn4->next = pn3; pn1->next = pn4; print_list(phead); // 2 -> 1 -> 4 -> 3 return 0; }