Given the class: CNode { int data node *next }; There are 5 nodes: pHead -> Node(data=1) -> Node(data=2) -> Node(data=3) -> Node(data=4) -> Node(data=5) -> null a) describe how to delete the node with data == 4 b) given that pHead=next.next, what node does pHead point to ? c) given just the head pointer, is it possible to print out the data in the entire list? How ?
Sigiloso
I am assuming that there are graphical glitches or something where it says "->", but I'll also assume that these are all part of a Linked List and give my answers accordingly: 1. Iterate through the Nodes via Node = Node.next (make sure to keep track of the Head node somehow) until you reach n-1 Nodes (in this case, you'd stop at Node(data=3) since you want to remove Node(data=4)). Then, you simply make that Node's next equal its NEXT'S next (Node.next = Node.next.next). 2. This one seems a little tricky, due to wording. They say there are only 5 Nodes, but there are technically 6 when you include the head, as you should. However, I will assume they are implying that we do not count the Head in the total count of nodes and that pHead.next points to Node(data=1). This would mean that its next.next would point to Node(data=1)'s next, which is clearly Node(data=2). 3. Yes, though there are several ways. The most simple way would be to make a copy of pHead and use that copy to iterate though the .next's. This would preserve the original pHead and not lose track of the Nodes. Another way would be to make a recursive function to iterate through the Linked List, and at each "iteration" of the recursion, the currently inspected Node's .next will be passed as a parameter. This will preserve the pHead, since there is no re-assignment of it throughout the recursive process. The single most important thing to keep in mind when handling Linked Lists is retaining the head pointer (unless the list is Doubly Linked, in which case the preservation of at least the head OR the tail is key). If you lose that pointer (or both for Doubly), you lose your entire Linked List.