#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 p 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 << "*** 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 node *ptemp; // delete the head node if (phead) // make sure the list is not empty!!! { ptemp = phead; // remember the address of the current head node! phead = phead->next; // point to the second node in the list delete ptemp; // delete the removed node } print_list(phead); // 1 -> 4 -> 3 // delete a non-head node FOLLOWING #1 from the middle of the list ptemp = pn1->next; // remember the address of the node-to-be-deleted pn1->next = ptemp->next; // link over the node to be deleted delete ptemp; // delete the removed node print_list(phead); // 1 -> 3 return 0; }