Python Program To Add Elements To A Linked List
A linked list is a sequence of nodes in which each node contains data and a reference to the next node in the sequence. In Python, we can create a linked list using the built-in LinkedList
module provided by the collections
package. In this article, we will discuss how to add elements to a linked list in Python.
Creating a Linked List
Before we can add elements to a linked list, we must first create a linked list. To create a linked list in Python, we can use the LinkedList
class provided by the collections
package.
Here’s how we can create a linked list in Python:
from collections import LinkedList
linked_list = LinkedList()
This creates an empty linked list which we can begin adding elements to.
Adding Elements To a Linked List
Now that we have created a linked list, we can start adding elements to it. In Python, we can add elements to a linked list using the add
method provided by the LinkedList
class.
Here’s an example of how we can add elements to a linked list:
from collections import LinkedList
linked_list = LinkedList()
# Add a single element to the end of the list
linked_list.add('element 1')
# Add multiple elements to the end of the list
linked_list.add('element 2')
linked_list.add('element 3')
In the above example, we added a single element to the end of the list using the add
method. We can also add multiple elements to the end of the list by calling the add
method multiple times with different values.
Adding Elements to a Specific Position
In addition to adding elements to the end of a linked list, we can also add elements to a specific position in the list. To add an element to a specific position in the list, we can use the insert
method provided by the LinkedList
class.
Here’s an example of how we can add an element to a specific position in the list:
from collections import LinkedList
linked_list = LinkedList()
# Add multiple elements to the end of the list
linked_list.add('element 1')
linked_list.add('element 2')
linked_list.add('element 3')
# Add an element to a specific position
linked_list.insert(1, 'new element')
In the above example, we added the element 'new element'
to position 1 in the list using the insert
method. This shifts all elements after position 1 by one position to the right.
Conclusion
In this article, we discussed how to create a linked list in Python using the LinkedList
class provided by the collections
package. We also discussed how to add elements to a linked list at the end of the list and at a specific position in the list using the add
and insert
methods respectively. With this knowledge, you can create and manipulate linked lists in Python.