Question: By convention, lists are often printed in brackets with commas between
ID: 3619936 • Letter: Q
Question
Question:By convention, lists are often printed in brackets with commas between
the elements, as in [1, 2, 3].
As an exercise, modify printList so that it generates output in the above format.
def printList(node): while node: print node, node = node.next print To invoke this function, we pass a reference to the ?rst node: >>> printList(node1) 1 2 3 --
The reading materials for the above question is posted below.
---
Lists as Collections:
Lists are useful because they provide a way to assemble multiple objects into a
single entity, sometimes called a collection. In the example, the first node of the
list serves as a reference to the entire list.
To pass the list as an argument, we only have to pass a reference to the first
node. For example, the function printList takes a single node as an argument.
Starting with the head of the list, it prints each node until it gets to the end:
def printList(node):
while node:
print node,
node = node.next
To invoke this function, we pass a reference to the first node:
>>> printList(node1)
1 2 3
Inside printList we have a reference to the first node of the list, but there is no
variable that refers to the other nodes. We have to use the next value from each
node to get to the next node.
To traverse a linked list, it is common to use a loop variable like node to refer to
each of the nodes in succession.
This diagram shows the nodes in the list and the values that node takes on:
def printList(node): while node: print node, node = node.next print To invoke this function, we pass a reference to the ?rst node: >>> printList(node1) def printList(node): while node: print node, node = node.next print To invoke this function, we pass a reference to the ?rst node: >>> printList(node1) 1 2 3
Explanation / Answer
def printList(node): print '[', while node: print node, if node.next: print ',', node = node.next print ']'
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.