Notes on Assignment 1 code The “Sentinel” The root node is created in the list object because we are using a "sentinel" approach. This approach uses a single cell that is always present to represent an empty list. This is an alternative to having a null pointer represent an empty list. With the root sentinel an empty list is not null, it is always present, there is always an object there constituting "the list". To discover is the list has no data cells, you can ask the list object to tell it's size, or ask the list to tell if it is empty (if it has a method like "isEmpty()" ). A list with no data elements in it looks like this internally (memory layout of the objects): aList root constructor getRoot size function function 0 data 0 next null prev null The list will look this way when it is created new, and when it is cleared with the clear method, and when all elements are removed one at a time… all the ways a list can come to attain size 0. This assumes you add a size field to the list object to implement the size method in constant time ( O(1) “big oh of 1” ). The Node object installed in root when the list object is made is not ever used to contain actual data. We never intend to alter the value of the root data field after root is created, and we will never examine the data field of the root node. It is there simple because its type is Node, and the 0 we put in there is not important… it could be anything of type double. The sentinel root node is used to indicate the end of a list of cells (in this case the front end… in other applications it might flag the tail end) rather than using a null object pointer. This node is always there, and the list of data cells hangs off of it. The object structure looks this way after insert(new Node(12.5),0). The list has size 1. aList root constructor getRoot size data next prev function function data next prev 1 12.5 null 0 null The object structure looks this way after aList.insert(new Node(3.1415),1) . List size is 2. aList root constructor function getRoot function size data 2 12.5 data 0 next prev data next next prev prev null 3.1415 null If we now do aList.remove(0) the list looks like the following: aList root constructor getRoot size function function 1 data 3.1415 next null data 0 next prev null prev The cell that was in position 1 is relinked when the position 0 cell is unlinked… moving the cell that was in position 1 now into position 0. We adjust the list size counter down one. If we now do aList.remove(0) again, the list looks like the following: aList root constructor getRoot size function function 0 data 0 next null prev null This is the same as the original new list. We put two elements into the list, removed 2 elements, so the list should be empty again, with size 0. However, the sentinel node we installed as root is still there.
© Copyright 2025 Paperzz