6.2 Traversing Linked Lists - CSC148 Course Notes
6.2 Traversing Linked Lists - CSC148 Course Notes
For example, here is a LinkedList method that prints out every item in a linked list.
class LinkedList:
def print_items(self) -> None:
"""Print out each item in this linked list."""
curr = self._first
while curr is not None:
print(curr.item) # Note: this is the only line we needed to
curr = curr.next
And here is a LinkedList method that’s a bit more complicated but uses the same
traversal template. The goal of this method is to convert a linked list into a built-in Python
list, in a non-mutating fashion (i.e., by returning a Python list without changing the original
list).
def to_list(self) -> list:
"""Return a (built-in) list that contains the same elements as this
"""
items = []
curr = self._first
while curr is not None:
items.append(curr.item)
curr = curr.next
return items
Whenever you’re starting to write code to iterate through a linked list, your first step
should be to copy-and-paste this template into your code. But that’s the easy part; the
next part involves the thinking required to fill in the ellipsis ( ... ) and modify the template
to suit your particular needs. In the following weeks of this course, you’ll get lots of
practice with that. 😀
[1] The following code is written to be a nice lead-in to linked list traversal; please keep in
mind that there are better ways of iterating through a list in Python!
https://www.teach.cs.toronto.edu/~csc148h/notes/linked-lists/linked_list_traversal.html 3/3