Linked List
1. Linked list is a data structure where each element (called Node) is linked each other. So when accessing to any element, we just need a pointer to traverse the link from the head/front node to reach the target node. This feature is indeed strong where the List (i.e., array) is weak. When a list is defined to store elements, one block of memory is allocated to the list to contain the memory address of each element. Hence we can directly access to any element using list_name[index]. Notice the index refers to the number of iterations required to reach the target element from the start. However, when removing or inserting an element, the list has to re-organize the entire structure and every element is then affected. For a linked list, the removal and insertion of a node do not affect the entire structure but just the link between previous node,target node, and/or next node.
2. Implementation of Linked List
(1). Set up Node: each node has it's own value and the attribute 'next_'
class Node:
def __init__(self, value, next_ = None)
self.value = value
self.next_ = next_
(2). Set up Linked List: a linked list can be initialized as an empty structure with empty 'front' and/or 'back' node.
class LinkedList:
def __init__(self):
self.front = None
self.back = None
self.size = 0
(3). Set up operations: Append and Reverse
Append is to add new element to the linked list after current back node. So, for a non-empty linked list, the first step is to have the back node link to a new node. Next we reconfigure the back node as the node newly added.
class LinkedList:
def append(self, value):
new_node = Node(value)
if self.size == 0:
self.front = self.back = new_node
else:
self.back.next_ = new_node
self.back = new_node
self.size += 1
Reverse is to reconfigure every node by breaking and rebuilding its link: from "front-->node1-->node2-->back" to "back<--node1<--node2<--front". So we just change the direction of link for each node rather than the entire structure. First of all, we need a pointer to traverse the linked list. Next a while loop is established for the pointer to loop over the linked list. At each iteration, the pointer firstly store its next node because the link to the next node will be broken. Then the pointer has the node currently scanned link to the previous node, which simultaneously breaks the link to the next node. To exit the iteration, the pointer moves to next node (this is why we must store the next node at the beginning of the iteration). Finally, after the loop is ended, we reconfigure the front and back node.
class LinkedList:
def reverse(self):
if self.size < 2:
return
else:
current_node = self.front.next_
previous_node = self.front
self.front.next_ = None
while current_node:
next_node = current_node.next_
current_node.next_ = previous_node
previous_node = current_node
current_node = next_node
self.back = self.front
self.front = previous_node
End of the post
No comments:
Post a Comment