7.4 Prepending Nodes to a Linked Listlinked list prepending worst-case:
When working with an unordered list, new values can be inserted at any point within the list. Since we only maintain the head reference as part of the list structure, we can simply prepend new items with little effort. Prepending a node can be done in constant time since no traversal is required. The implementation is provided below: # Given the head reference, prepend an item to a singly linked list. newNode = ListNode(item) newNode.next = head head = newNode Suppose we want to add the value 96 to our example list Adding an item to the front of the list requires several steps. First, we must create a new node to store the new value newNode = ListNode(96) and then set its newNode.next = head We then adjust head = newNode Note the order of the new links since it is important we first link the new node into the list before modifying the head reference. Otherwise, we lose our external reference to the list and in turn, we lose the list itself. The results, after linking the new node into the list are shown below. When modifying or changing links in a linked list, we must consider the case when the list is empty. For our implementation, the code works perfectly as illustrated in Figure 7.4.1. The Question 7.4.1
Consider the sequence of statements used to prepend a node to a linked list. newNode = ListNode(item) newNode.next = head head = newNode What would happen if the last two statements were reversed and The nodes that comprise the current list would be destroyed. The Question 7.4.2
Suppose we want to build a linked list from the contents of a Python list by prepending each element of the Python list to the linked list. Design and implement a Python function One possible solution is provided below: def buildList(theValues) : head = None for element in theValues : newNode = ListNode(element) newNode.next = head head = newNode return head
|