Docsity

Linked Lists: A Recursive Data Structure, Exams of Electrical and Electronics Engineering

Toggle sidebar
bg1
Chapter 17
Linked lists
17.1 Embedded references
We have seen examples of attributes that refer to other objects, which we called
embedded references (see Section 12.8). A common data structure, the
linked list, takes advantage of this feature.
Linked lists are made up of nodes, where each node contains a reference to the
next node in the list. In addition, each node contains a unit of data called the
cargo.
A linked list is considered a recursive data structure because it has a recur-
sive definition.
A linked list is either:
•the empty list, represented by None,or
•a node that contains a cargo object and a reference to a linked
list.
Recursive data structures lend themselves to recursive methods.
17.2 The Node class
As usual when writing a new class, we’ll start with the initialization and str
methods so that we can test the basic mechanism of creating and displaying the
new type:
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Linked Lists: A Recursive Data Structure and more Exams Electrical and Electronics Engineering in PDF only on Docsity!

Chapter 17

Linked lists

17.1 Embedded references

We have seen examples of attributes that refer to other objects, which we called embedded references (see Section 12.8). A common data structure, the linked list, takes advantage of this feature.

Linked lists are made up of nodes, where each node contains a reference to the next node in the list. In addition, each node contains a unit of data called the cargo.

A linked list is considered a recursive data structure because it has a recur- sive definition.

A linked list is either:

  • the empty list, represented by None, or
  • a node that contains a cargo object and a reference to a linked list.

Recursive data structures lend themselves to recursive methods.

17.2 The Node class

As usual when writing a new class, we’ll start with the initialization and str methods so that we can test the basic mechanism of creating and displaying the new type:

180 Linked lists

class Node: def init(self, cargo=None, next=None): self.cargo = cargo self.next = next

def str(self): return str(self.cargo)

As usual, the parameters for the initialization method are optional. By default, both the cargo and the link, next, are set to None.

The string representation of a node is just the string representation of the cargo. Since any value can be passed to the str function, we can store any value in a list.

To test the implementation so far, we can create a Node and print it:

>>> node = Node("test") >>> print node test

To make it interesting, we need a list with more than one node:

>>> node1 = Node(1) >>> node2 = Node(2) >>> node3 = Node(3)

This code creates three nodes, but we don’t have a list yet because the nodes are not linked. The state diagram looks like this:

cargo next

node

None

cargo next

node

None

cargo next

node

None

To link the nodes, we have to make the first node refer to the second and the second node refer to the third:

>>> node1.next = node >>> node2.next = node

The reference of the third node is None, which indicates that it is the end of the list. Now the state diagram looks like this:

182 Linked lists

node

cargo y

1 cargo y

node

cargo y

node

None

node

By convention, lists are often printed in brackets with commas be- tween the elements, as in [1, 2, 3]. As an exercise, modify printList so that it generates output in this format.

17.4 Lists and recursion

It is natural to express many list operations using recursive methods. For ex- ample, the following is a recursive algorithm for printing a list backwards:

  1. Separate the list into two pieces: the first node (called the head); and the rest (called the tail).
  2. Print the tail backward.
  3. Print the head.

Of course, Step 2, the recursive call, assumes that we have a way of printing a list backward. But if we assume that the recursive call works—the leap of faith—then we can convince ourselves that this algorithm works.

All we need are a base case and a way of proving that for any list, we will eventually get to the base case. Given the recursive definition of a list, a natural base case is the empty list, represented by None:

def printBackward(list): if list == None: return head = list tail = list.next printBackward(tail) print head,

The first line handles the base case by doing nothing. The next two lines split the list into head and tail. The last two lines print the list. The comma at the end of the last line keeps Python from printing a newline after each node.

17.5 Infinite lists 183

We invoke this method as we invoked printList:

>>> printBackward(node1) 3 2 1

The result is a backward list.

You might wonder why printList and printBackward are functions and not methods in the Node class. The reason is that we want to use None to represent the empty list and it is not legal to invoke a method on None. This limitation makes it awkward to write list-manipulating code in a clean object-oriented style.

Can we prove that printBackward will always terminate? In other words, will it always reach the base case? In fact, the answer is no. Some lists will make this method crash.

17.5 Infinite lists

There is nothing to prevent a node from referring back to an earlier node in the list, including itself. For example, this figure shows a list with two nodes, one of which refers to itself:

cargo next

1 cargo next

list

If we invoke printList on this list, it will loop forever. If we invoke printBackward, it will recurse infinitely. This sort of behavior makes infinite lists difficult to work with.

Nevertheless, they are occasionally useful. For example, we might represent a number as a list of digits and use an infinite list to represent a repeating fraction.

Regardless, it is problematic that we cannot prove that printList and printBackward terminate. The best we can do is the hypothetical statement, ā€œIf the list contains no loops, then these methods will terminate.ā€ This sort of claim is called a precondition. It imposes a constraint on one of the parame- ters and describes the behavior of the method if the constraint is satisfied. You will see more examples soon.

17.8 Wrappers and helpers 185

def removeSecond(list): if list == None: return first = list second = list.next

make the first node refer to the third

first.next = second.next

separate the second node from the rest of the list

second.next = None return second

Again, we are using temporary variables to make the code more readable. Here is how to use this method:

>>> printList(node1) 1 2 3 >>> removed = removeSecond(node1) >>> printList(removed) 2 >>> printList(node1) 1 3

This state diagram shows the effect of the operation:

cargo next

1 cargo next

second

cargo next

None

first

What happens if you invoke this method and pass a list with only one element (a singleton)? What happens if you pass the empty list as an argument? Is there a precondition for this method? If so, fix the method to handle a violation of the precondition in a reasonable way.

17.8 Wrappers and helpers

It is often useful to divide a list operation into two methods. For example, to print a list backward in the conventional list format [3, 2, 1] we can use the printBackward method to print 3, 2, but we need a separate method to print the brackets and the first node. Let’s call it printBackwardNicely:

186 Linked lists

def printBackwardNicely(list) : print "[", if list != None : head = list tail = list.next printBackward(tail) print head, print "]",

Again, it is a good idea to check methods like this to see if they work with special cases like an empty list or a singleton.

When we use this method elsewhere in the program, we invoke printBackwardNicely directly, and it invokes printBackward on our be- half. In that sense, printBackwardNicely acts as a wrapper, and it uses printBackward as a helper.

17.9 The LinkedList class

There are some subtle problems with the way we have been implementing lists. In a reversal of cause and effect, we’ll propose an alternative implementation first and then explain what problems it solves.

First, we’ll create a new class called LinkedList. Its attributes are an integer that contains the length of the list and a reference to the first node. LinkedList objects serve as handles for manipulating lists of Node objects:

class LinkedList : def init(self) : self.length = 0 self.head = None

One nice thing about the LinkedList class is that it provides a natural place to put wrapper functions like printBackwardNicely, which we can make a method of the LinkedList class:

class LinkedList: ... def printBackward(self): print "[", if self.head != None: self.head.printBackward() print "]",

188 Linked lists

have added the node but before we have incremented length, the invariant is violated. This kind of violation is acceptable; in fact, it is often impossible to modify an object without violating an invariant for at least a little while. Normally, we require that every method that violates an invariant must restore the invariant.

If there is any significant stretch of code in which the invariant is violated, it is important for the comments to make that clear, so that no operations are performed that depend on the invariant.

17.11 Glossary

embedded reference: A reference stored in an attribute of an object.

linked list: A data structure that implements a collection using a sequence of linked nodes.

node: An element of a list, usually implemented as an object that contains a reference to another object of the same type.

cargo: An item of data contained in a node.

link: An embedded reference used to link one object to another.

precondition: An assertion that must be true in order for a method to work correctly.

fundamental ambiguity theorem: A reference to a list node can be treated as a single object or as the first in a list of nodes.

singleton: A linked list with a single node.

wrapper: A method that acts as a middleman between a caller and a helper method, often making the method easier or less error-prone to invoke.

helper: A method that is not invoked directly by a caller but is used by another method to perform part of an operation.

invariant: An assertion that should be true of an object at all times (except perhaps while the object is being modified).