LinkedList, a common recursive
data structure, has been our topic in both lectures and tutorials in the past
two weeks. It is commonly used to solve problems that are created by the
built-in list, an example would be the
class Queue I discussed in the beginning of the year.In class Queue we created, we used list to
store and modify information. When we need to remove a item from the beginning
of the list as required, every other item except the removed item will need to
shift forward by one index, which would take a remarkable long time if the list
is large. However, if we use LinkedList to store information, we could solve this problem.
LinkedList
is defined recursively. A LinkedList is either empty, which is represented by None, or an object that contains a cargo
object and a reference to a LinkedList. A simple example of __init__ would be:
def
__init__(self, item, rest: 'LinkedList') ->
None:
self.item
= item
self.rest
= rest
We can add more instance variables to give LinkedList more attributes, such as self.empty, self.size, etc. On the other hand, we can make methods or a helper class to make LinkedList more like a built-in list. For example, we can have __getitem__, __setitem__, __delitem__, and insert to have access to the item on a specific index, as well as __eq__, __str__, __repr__, and reverse.
We can add more instance variables to give LinkedList more attributes, such as self.empty, self.size, etc. On the other hand, we can make methods or a helper class to make LinkedList more like a built-in list. For example, we can have __getitem__, __setitem__, __delitem__, and insert to have access to the item on a specific index, as well as __eq__, __str__, __repr__, and reverse.
We can make LinkedList infinite closer to built-in list while LinkedList has its own advantages. However, it also has disadvantages. There is a possibility that it becomes a infinite list. It will happen when self.rest refers to self, or some LinkedList that is before self.
There are still a lot things for me to discover about LinkedList. I will try to fully understand it, and flexibly switch between LinkedList and built-in list when I code. I believe it will help me solve a lot run-time problems like Queue in the future.

No comments:
Post a Comment