Wednesday 30 October 2013

Linked Lists and their efficiency


Aren't Python lists just based on arrays that consist of contiguous chunks of memory? But what if they didn't have to be contiguous ? What if we just want to add new elements into the memory without having to change the location of others ?

Now we can introduce a new data structure called Linked Lists which is simply a chain of connected nodes where each node contains a data field and a next field which points to the next node in the list. How do we reach to the end of the list ? We traverse the list by following each node's next pointer until we reach the end of our linked list. In most cases we have access to the first node which is called the head.

Adding and removing from Linked Lists
Adding a node replaces the last node reference to the new node that's being added and makes our old last node point to the new node as the next node in the list.
Deleting a node is a process that iterates the list looking for the node and and we look around the deleted node to make sure that the previous node now points to the following node as its next node.

Linked list efficiency:
Most operations that we apply to either end of our linked list do not depend on the size of the list but only one operation does which is removing from the end of the list .
Why ?!
Because removing from the end of the list requires a full traversal since we can't obtain our new tail just from tail.



No comments:

Post a Comment