Exercise 13 SLL Push method

My misunderstanding is within the push method. I understand the initial “if”, setting begin and end to the first node. But how are every other node after being set to self.begin.next?

class singleLinkedList(object):
    def __init__(self):
        self.begin = None
        self.end = None

    def push(self, val): 
        curNode = Node(val, None)

        if self.begin is None: 
            self.end = curNode
            self.begin = self.end
        else:
            self.end.next = curNode 
            self.end = curNode

After the first push self.begin == self.end. So the second time self.end.next == self.begin.next.

Does that help? Try and draw a diagram or something, keeping track of where begin and end point at each step.

@florian has the right idea, but go into the else clause of push and write a print statement that prints out what’s going on, or use pdb:

https://docs.python.org/3/library/pdb.html

And walk through it to see what’s going on. The idea is that it’s just taking the end and adding on end’s next, then moving end. But, watch it and see what it’s doing.

Thank you very much!

A free service run by Zed A. Shaw for learncodethehardway.org.