Previous Lecture Lecture 11 Next Lecture

Lecture 11, Tue 05/07

Linked Lists

Plan for today

Stack, Queue, Deque

Linked Lists vs. Lists

Lists:

Linked Lists:

Nodes

SongNode in-class activity: https://t.ly/HHoM7

Comparing nodes

How to compare two SongNode objects?

SongNode in-class activity: https://tinyurl.com/cs9songnode1

Benefits of Linked Lists

Question & Example SongList

Count number of nodes in a linked list:

def length(self):
  current = self.head
  count = 0
  while current != None:
    count += 1
    current = current.get_next()
  return count

Remove an element from the linked list:

def remove(self, item):
  current = self.head
  previous = None
  found = False
  # while loop to iterate through the linked list and find the node to remove

Check if linked list is empty or at the end of the list:

while not found:
  if current == None:
    return

Student Questions

Q: Why do you include a backslash (\) in a return statement? A: Backslashes are used to create a multiline statement, so when we use it in the return statement, we can write our and condition on multiple lines (to make it easier to see its parts)

Q: Assert statements when using comparison operators A: You need to include parentheses to indicate order of operations - eg: assert (pet1 < pet2) == True instead of assert pet1 < pet2 == True