#include struct node { node *next; int value; node (int i) { value = i; next = nullptr; } }; /** * 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 } } /** * Insert a node into the list. * * @param pp A pointer to the next pointer in the node preceeding the new node. * @param pn A pointer to the node to insert. *****************************************************************/ static void insert_node(node **pp, node *pn) { pn->next = *pp; *pp = pn; } /** * Demonstrate singly-linked list insertions. *****************************************************************/ int main() { node *phead = nullptr; print_list(phead); std::cout << "*** insert a new node into an empty list" << std::endl; node *pn1 = new node(1); insert_node(&phead, pn1); print_list(phead); // 1 std::cout << "*** insert a new node at the head of a non-empty list" << std::endl; node *pn2 = new node(2); insert_node(&phead, pn2); 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(3); insert_node(&pn1->next, pn3); 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(4); insert_node(&pn1->next, pn4); print_list(phead); // 2 -> 1 -> 4 -> 3 return 0; }