#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 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; } /** * Delete a node from the list. * * @param pp A pointer to the next pointer in the node * preceeding the node to delete. *****************************************************************/ static void delete_node(node **pp) { if (*pp == nullptr) // make sure we are actually deleting a node! return; node *ptemp = *pp; // remember the address of the node to delete *pp = (*pp)->next; // remove the node from the list delete ptemp; // delete the node } /** * Demonstrate singly-linked list insertions and deletions. *****************************************************************/ int main() { node *phead = nullptr; print_list(phead); std::cout << "*** build a list" << std::endl; node *pn1 = new node(1); insert_node(&phead, pn1); node *pn2 = new node(2); insert_node(&phead, pn2); node *pn3 = new node(3); insert_node(&pn1->next, pn3); node *pn4 = new node(4); insert_node(&pn1->next, pn4); print_list(phead); // 2 -> 1 -> 4 -> 3 // delete the head node from the list delete_node(&phead); print_list(phead); // 1 -> 4 -> 3 // delete a non-head node FOLLOWING #1 from the middle of the list delete_node(&pn1->next); print_list(phead); // 1 -> 3 // delete all the nodes in the list while(phead) delete_node(&phead); return 0; }