Linked lists are a data structure that are used to store a sequence of data. They are used to store data in a linear fashion. The data is stored in nodes, which are connected to each other. The first node is called the head and the last node is called the tail. The head and tail are not connected to each other. The head is connected to the first node and the tail is connected to the last node.
Big O
The following is a table of the Big O notation for operations of linked lists and lists.
Under the hood
A node is actually a class that has two properties: value and next. The value is the data that is stored in the node and the next is a reference to the next node. A node can be seen as a dictionary with two keys: value and next. For example,
{"value":4,"next":None}
You can think about a linked list as a set of nested dictionaries.
definsert(self,index,value):if index <0or index > self.length:returnFalseif index ==0:return self.prepend(value)if index == self.length:return self.append(value) new_node =Node(value) temp = self.get(index -1) new_node.next = temp.next temp.next = new_node self.length +=1returnTrue
Remove
defremove(self,index):if index <0or index >= self.length:returnNoneif index ==0:return self.pop_first()if index == self.length -1:return self.pop() pre = self.get(index -1) temp = pre.next pre.next = temp.next temp.next =None self.length -=1return temp
Reverse
defreverse(self): temp = self.head self.head = self.tail self.tail = temp after = temp.next before =Nonefor _ inrange(self.length): after = temp.next temp.next = before before = temp temp = after