LMPTHW ex13 create list mimicking Single Linked List

Hello all,

I am trying to solve the exercise:
‘WARNING! Take the time now to figure out how to manually build a list using just the
SingleLinkedListNode class and then manually walk through it. This is a good
45-minute hack spike to try at this point in the exercise.’ (LMPTHW, pg. 51)

Problem:
I do not understand:

  1. what is exactly meant by ‘manually’ in the exercise description above.
  2. the code below and how to create instances of the class that represent ‘nodes’ in a ‘Single Linked List’.
1 class SingleLinkedListNode(object):
2
3 def __init__(self, value, nxt):
4 self.value = value
5 self.next = nxt
6
7 def __repr__(self):
8 nval = self.next and self.next.value or None
9 return f"[{self.value}:{repr(nval)}]"

My code is:

head = SingleLinkedListNode(None, 1)  
"""the head of the SLL has no value, but contains the address of the next node, given that 1 represents the address of the next node"""
node1 = SingleLinkedListNode(10, 2) # self.value = 10, self.next =2

My code gives an error (es expected)
ERROR:
nval = self.next and self.next.value or None
AttributeError: ‘int’ object has no attribute ‘value’

I understand the error:
for variable ‘head’ self.next = 2 (integer), but, the program expects another object of class SingleLinkedListNode. But somehow this would mean that the 2nd parameter of head (the object) is already supposed to be created (but I do not see how I can create it before creating head).

You’re almost there, I think you just need to work on this more. You have an error, so find out why you have this error. What is supposed to go in nxt parameters? Is it a number? Nope, it’s another node right? “node” means the SingleLinkedListNode objects, so you just have to construct those manually, one line at a time, then go through them manually, one line at a time.

Thank you.Your comment helped.

Would something like this be OK?

list_of_nodes = []
head = SingleLinkedListNode(None, None)
list_of_nodes.append(head)
print(list_of_nodes)
node1 = SingleLinkedListNode(10, None)
head = SingleLinkedListNode(None, node1)
list_of_nodes[-1] = head
list_of_nodes.append(node1)
print(list_of_nodes)
node2 = SingleLinkedListNode(20, None)
node1 = SingleLinkedListNode(10, node2)
list_of_nodes[-1] = node1
list_of_nodes.append(node2)
print(list_of_nodes)

Perfect. Keep going.

1 Like