Sunday, 29 March 2015

impression of week#8 - linked list (week#9)

Last week, we learned a new data structure -- linked list.

Linked list is a linear sequence of nodes with each node referring to its next node(child).

Firstly, we are introduced LLNode -- linked list node. LLNodes are the nodes in a linked list. The following is the code for its init method. As is mentioned before, each node in the linked list has a value(self.value) and refers to a child(self.nxt).

And then it comes to LinkedList:



Linked list has front(self.front) referring to the first node, and a back(self.back) referring the last node. The size is the number of nodes in it. 

Interestingly, as can be seen in the code of the __str__ method, it doesn't "return all nodes", instead, it just returns the "front", which confused me a lot at the beginning. Isn't it returning just one node at the front? Is there anything wrong with the prof's code? And then I tried printing it in wing -- it returns the whole linked list! What a surprise! So I continued to print the front, and get the same result. I didn't understand it until I read Huan Ling's SLOG. Let's recall the concept of linked list node first: It's not just a node with a value, but also a reference to it's child -- the next LLNode, namely, the "front" is not just a single node, it also refers to its next node. The next node also refers to its next node, and so on. That's why when I print front, I get the expression of the whole node.

After practicing it in the lab, I find that the greatest benefit of the linked list is that it's easy to insert and delete nodes. We can change the node anywhere we like without shifting the other nodes.




The last thing to note is that, before writing code for the linked list, it's super useful to draw pictures first and keep track of what's going on, since it's very easy to get lost and mess up when we write the code.

No comments:

Post a Comment