#include struct node { node *next; int value; node (int i) { value = i; } }; /** * 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 head of the list. * * @param phead A pointer to the head pointer. * @param p A pointer to the node to insert. *****************************************************************/ static void insert_front(node **phead, node *p) { p->next = *phead; *phead = p; } /** * Insert a node into the list after the node given by prev. * * @param prev A pointer to the node to insert after. * @param p A pointer to the node to insert. *****************************************************************/ static void insert_after(node *prev, node *p) { p->next = prev->next; prev->next = p; } /** * 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_front(&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_front(&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_after(pn1, 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_after(pn1, pn4); print_list(phead); // 2 -> 1 -> 4 -> 3 return 0; }