The List is the same as arrays irrespective it can store different data types in it. We can access the list by using the start and end range which can be altered by using custom step function as the third argument.
Let’s define a variable named myList and declare a list of numbers from 1 to 9 in it.
List Slicing means accessing the particular element by index or slice or cut a particular range of elements from the List.
Read => Create and write MetaData to a file – Python
Source Code
Output
In single linked list each node of the list has two components, the actual value of the node and the reference to the next node in the linked list. In the doubly linked list, each node has three components: the value of the node, the reference to the previous node, and the reference to the next node. For the start node of the doubly linked list, the reference to the previous node is null. Similarly, for the last node in the doubly linked list, the reference to next node is null.
Following are some of the pros and cons of a doubly linked list:
Pros
Unlike a single linked list, the doubly linked list can be traversed and searched in both directions. The reference to the next node helps in traversing the node in the forward direction while the references to the previous nodes allow traversal in the backward direction.
Basic operations such as insertion and deletion are easier to implement in the doubly linked lists since, unlike single linked lists, we do not need to traverse to the predecessor node and store its reference. Rather, in a doubly linked list the reference of the predecessor node can be retrieved from the node that we want to delete.
Cons
One of the major drawbacks of the doubly linked list is that you need more memory space to store one extra reference for each node.
A few additional steps are required to be performed in order to perform insertion and deletion operations.
In this section, we will see how we can create a very simple doubly linked list in Python. If you have read Part 1 and Part 2 of this series of articles, the code should be pretty straight-forward.
As always, let's first create a class for the single node in the list. Add the following code to your file:
You can see in the above code, we create a Node
class with three member variables: item
, nref
, and pref
. The item
variable will store the actual data for the node. The nref
stores the reference to the next node, while pref
stores the reference to the previous node in the doubly linked list.
Next, we need to create the DoublyLinkedList
class, which contains different doubly linked list related functions. Add the following code:
Throughout this article we will keep adding functions to this class.
Inserting Items in Doubly Linked List
In this section, we will see the different ways of inserting items in a doubly linked list.
Inserting Items in Empty List
The easiest way to insert an item in a doubly linked list is to insert an item in the empty list. The following script inserts an element at the start of the doubly linked list:
In the script above, we define a method insert_in_emptylist()
. The method first checks whether the self.start_node
variable is None
or not. If the variable is None
, it means that the list is actually empty. Next, a new node is created and its value is initialized by the value passed as a parameter to the data
parameter of the insert_in_emptylist()
function. Finally, the value of self.start_node
variable is set to the new node. In case if the list is not empty, a message is simply displayed to the user that the list is not empty.
Add the insert_in_emptylist()
method to the DoublyLinkedList
class that you created earlier.
Inserting Items at the Start
To insert an item at the beginning of the doubly linked list, we have to first check whether the list is empty or not. If the list is empty, we can simply use the logic defined in the insert_in_emptylist()
to insert the element since in an empty list, the first element is always at the start.
Else, if the list is not empty, we need to perform three operations:
For the new node, the reference to the next node will be set to self.start_node
.
For the self.start_node
the reference to the previous node will be set to the newly inserted node.
Finally, the self.start_node
will become the newly inserted node.
The following script inserts an item at the start of the doubly linked list:
Add the insert_at_start()
method to the DoublyLinkedList
class that you created earlier.
Inserting Items at the End
Inserting an element at the end of the doubly linked list is somewhat similar to inserting an element at the start. At first, we need to check if the list is empty. If the list is empty then we can simply use the insert_in_emptylist()
method to insert the element. If the list already contains some element, we traverse through the list until the reference to the next node becomes None
. When the next node reference becomes None
it means that the current node is the last node.
The previous reference for the new node is set to the last node, and the next reference for the last node is set to the newly inserted node. The script for inserting an item at the last node is as follows:
Add the insert_at_end()
method to the DoublyLinkedList
class that you created earlier.
Inserting Item after another Item
To insert an item after another item, we first check whether or not the list is empty. If the list is actually empty, we simply display the message that the "list is empty".
Otherwise we iterate through all the nodes in the doubly linked list. In case if the node after which we want to insert the new node is not found, we display the message to the user that the item is not found. Else if the node is found, it is selected and we perform four operations:
Set the previous reference of the newly inserted node to the selected node.
Set the next reference of the newly inserted node to the next reference of the selected.
If the selected node is not the last node, set the previous reference of the next node after the selected node to the newly added node.
Finally, set the next reference of the selected node to the newly inserted node.
The script for inserting item after another item is as follows:
Add the insert_after_item()
method to the DoublyLinkedList
class that you created earlier.
Inserting Item before another Item
To insert an item before another item, we first check whether or not the list is empty. If the list is actually empty, we simply display the message that the "list is empty".
Otherwise we iterate through all the nodes in the doubly linked list. In case if the node before which we want to insert the new node is not found, we display the message to the user that the item is not found. Else if the node is found, it is selected and we perform four operations:
Set the next reference of the newly inserted node to the selected node.
Set the previous reference of the newly inserted node to the previous reference of the selected.
Set the next reference of the node previous to the selected node, to the newly added node.
Finally, set the previous reference of the selected node to the newly inserted node.
The script for adding item before another item in a doubly linked list is as follows:
Add the insert_before_item()
method to the DoublyLinkedList
class that you created earlier.
Traversing a Doubly Linked List
Traversing a doubly linked list is very similar to traversing a single linked list. The script is as follows:
Add the traverse_list()
method to the DoublyLinkedList
class that you created earlier.
Deleting Elements from Doubly Linked List
Like insertion, there can be multiple ways to delete elements from a doubly linked list. In this section, we will review some of them.
Deleting Elements from the Start
The easiest way to delete an element from a doubly linked list is from the start. To do so, all you have to do is set the value of the start node to the next node and then set the previous reference of the start node to None
. However before we do that we need to perform two checks. First, we need to see if the list is empty. And then we have to see if the list contains only one element or not. If the list contains only one element then we can simply set the start node to None
. The following script can be used to delete elements from the start of the doubly linked list.
Add the delete_at_start()
method to the DoublyLinkedList
class that you created earlier.
Deleting Elements from the End
To delete the element from the end, we again check if the list is empty or if the list contains a single element. If the list contains a single element, all we have to do is to set the start node to None
. If the list has more than one element, we iterate through the list until the last node is reached. Once we reach the last node, we set the next reference of the node previous to the last node, to None
which actually removes the last node. The following script can be used to delete the element from the end.
Add the delete_at_end()
method to the DoublyLinkedList
class that you created earlier.
Deleting Elements by Value
Deleting an element by value is the trickiest of all the deletion functions in doubly linked lists since several cases have to be handled in order to remove an element by value. Let's first see how the function looks like and then we will see the explanation of the individual piece of code.
In the above script we create delete_element_by_value()
function that takes the node value as parameter and deletes that node. At the beginining of the function we check if the list is empty or not. If the list is empty we simply display the user that the list is empty.
This logic is implemented in the following piece of code:
Next, we check if the list has a single element and that element is actually the element we want to delete. If the only element is the one that we want to delete, we simply set the self.start_node
to None
which means that the list will now have no item. If there is only one item and that is not the item that we want to delete, we will simply display the message that item to be deleted is not found.
The following piece of code implements this logic:
Next, we handle the case where the list has more than one items but the item to be deleted is the first item. In that case we simply execute the logic that we wrote for the method delete_at_start()
. The following piece of code deletes an element from the start in case of multiple items:
Finally, if the list contains multiple items and the item to be deleted is not the first item, we traverse all the elements in the list except the last one and see if any of the nodes has the value that matches the value be deleted. If the node is found, we perform the following two operations:
Set the value of the next reference of the previous node to the next reference of the node to be deleted.
Set the previous value of the next node to the previous reference of the node to be deleted.
Finally, if the node to be deleted is the last node, the next reference of the node previous to the last node is set to None
. The following script implements this logic:
Add the delete_element_by_value()
method to the DoublyLinkedList
class that you created earlier.
Reversing a Doubly Linked List
To reverse a doubly linked list, you basically have to perform the following operations:
The next reference of the start node should be set none because the first node will become the last node in the reversed list.
The previous reference of the last node should be set to None
since the last node will become the previous node.
The next references of the nodes (except the first and last node) in the original list should be swapped with the previous references.
The script for reversing a doubly linked list is as follows:
Add the reverse_linked_list()
method to the DoublyLinkedList
class that you created earlier.
Testing Doubly Linked List Functions
In this section, we will test the doubly linked functions that we created in the previous sections.
Let's first create the object of the DoublyLinkedList
class. Execute the following script:
Testing Insertion Functions
Let's test the insertion functions first. We'll first add elements in the empty list. Execute the following script:
Now if you traverse the list, you should see 50 as the only element in the list as shown below:
Output:
Now let's add a few elements at the start. Execute the following script:
Now if you traverse the list, you should see the following elements in the list:
To add the elements at the end, execute the following script:
Now if you traverse the doubly linked list, you should see the following elements:
Let's insert an element after 50.
Now the list should look like this:
Finally, let's add an element before item 29.
The list at this point of time, should contain the following elements:
Testing Deletion Functions
Let's now test the deletion functions on the items that we inserted in the last sections. Let's first delete an element from the start.
Item 18 will be removed and the list will now look like this:
Similarly, the following script deletes the element from the end of the doubly linked list:
Traversing the list now will return the following items:
Finally, you can also delete the elements by value using the delete_element_by_value()
function as shown below:
If you traverse the list now, you will see that item 65 will be deleted from the list.
Testing Reverse Function
Finally, let's reverse the list using the reverse_linked_list()
function. Execute the following script:
Now if you traverse the list, you will see the reversed linked list:
The doubly linked list is extremely useful specifically when you have to perform lots of inserts and delete operations. The links to the previous and next nodes make it very easy to insert and delete new elements without keeping track of the previous and next nodes.
In this article, we saw how doubly linked list can be implemented with Python. We also saw different ways to perform insert and delete operations on doubly linked list. Finally we studied how to reverse a doubly linked list.
A Linked List is a data structure in which the objects are arranged in a linear order. Unlike an array, however, in which the linear order is determined by the array indices, the order in a linked list is determined by a pointer in each object.
Each element of a doubly linked list is an object with an attribute key and two other pointer attributes next and prev.
A list may have one of several forms. It may be either singly linked or doubly linked, it may be sorted or not, and it may be circular or not.
Given a linked list, in addition to the next pointer, each node has a child pointer that can point to a separate list. With the head node, flatten the list to a single-level linked list.
Reverse a singly linked list. Implement it recursively and iteratively.
Convert a binary tree to a doubly circular linked list.
Implement an LRU cache with O(1) runtime for all its operations.
Check distance between values in linked list.
A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
Given a singly linked list (a list which can only be traversed in one direction), find the item that is located at 'k' items from the end. So if the list is a, b, c, d and k is 2 then the answer is 'c'. The solution should not search the list twice.
How can you tell if a Linked List is a Palindrome?
Unlike arrays, linked lists do not have objective positions in the list. Instead, they have relational positions based on their surrounding nodes.
The first node in a linked list is called the head node, and the final is called the tail node, which has a null
pointer.
Linked lists can be singly or doubly linked depending if each node has just a single pointer to the next node or if it also has a second pointer to the previous node.
You can think of linked lists like a chain; individual links only have a connection to their immediate neighbors but all the links together form a larger structure.
Python does not have a built-in implementation of linked lists and therefore requires that you implement a Node
class to hold a data value and one or more pointers.
Advantages:
Efficient insertion and deletion of new elements
Simpler to reorganize than arrays
Useful as a starting point for advanced data structures like graphs or trees
Disadvantages:
Storage of pointers with each data point increases memory usage
Must always traverse the linked list from Head node to find a specific element
Applications:
Building block for advanced data structures
Solutions that call for frequent addition and removal of data
Print the middle element of a given linked list
Remove duplicate elements from a sorted linked list
Check if a singly linked list is a palindrome
Merge K sorted linked lists
Find the intersection point of two linked lists
A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
This is an example of a double ended, doubly linked list.
Each link references the next link and the previous one.
A Doubly Linked List (DLL) contains an extra pointer, typically called previous
pointer, together with next pointer and data which are there in singly linked list.
Advantages over SLL - It can be traversed in both forward and backward direction.
Delete operation is more efficient
Test:
For more background on the different types of data structures in Python, check out the following articles:
A Linked List is a linear data structure. They are a sequence of data, connected together by links or pointers.
Linked Lists are a chain of nodes, connected together by links. Every node (fundamental block of a linked list) contains the following fields:
Data -> The item to be stored in the node.
Next -> The link or reference to the next node.
Due to their dynamic size allocation and ease of insertion/deletion, linked lists are applied in a lot of use cases.
They’re used to implement a lot of complex data structures like the adjacency list in graphs.
They are used for lifecycle management in operating systems.
A playlist in a music application is implemented using a doubly linked list.
Blockchain, a complex data structure that is used for cryptocurrencies and ledgers use a linked list at their core.
There are two main types of Linked Lists:
Singly Linked Lists
Doubly Linked Lists
In the following example, we’ll implement a singly linked list from scratch in Python. This contains the following methods:
ll.search(head, data)
-> Search the given element in the Linked List.
ll.print_list()
-> Print the linked list.
ll.size()
-> Return the length of the linked list.
ll.insert(ele)
-> Insert the given node into the linked list.
ll.delete(data)
-> Delete the given element from the linked list.
A doubly linked list is similar to a singly linked list. It differs in that it also contains a link to the previous node.
dll.addNodeLast(x)
-> Adds a node at the right end of the linked list.
dll.insertNode(pos, x)
-> Adds a node at the position specified.
dll.removeNode(x)
-> Removes the specified node.
dll.showReverse()
-> Prints the linked list in reverse.
dll.show()
-> Prints the linked list.
First, try implementing the Linked Lists as shown above, and then try running them. Once you’ve mastered the implementation, try the given problem-sets to master linked lists.
are a sequential collection of data that uses relational pointers on each data node to link to the next node in the list.
In a linked list, the first node is called the head and the last node is determined by the condition that the next points to a null value.
We implement the following methods for the Doubly Linked List data structure:
Merge Two Sorted Lists -
Remove nth Node from the End of the List -
Rotate List -
Palindrome Linked List -
Construct a Doubly Linked List from 2D Matrix -
Reverse a Doubly Linked List -