Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to add element to first and last position of linked list
In Python, a linked list is a linear data structure that consists of a chain of nodes, where each node contains a value and a reference to the next node in the chain.
In this article, we will be discussing how to add an element to the first and last position of a linked list in Python.
Linked List in Python
A linked list is a referential data structure that holds a group of elements. It is similar to an array but while data is stored in contiguous memory locations in an array, in a linked list the data is not bound by that condition. The data is stored in a random manner in memory rather than sequentially.
This raises the question: how can we access elements in a linked list? The answer is that in a linked list, one element points to another until the end of the list.
The beginning and end of the list are considered special positions. The beginning is called the head and points to the first element. The last element is special because it points to None.
Head ? data_1 ? data_2 ? ? ? data_n ? None
Traversing the linked list is simple: start from the head and access the next node, continuing until we find a node whose next node is None.
Adding Elements at the Beginning
To add data at the beginning of the linked list, we must consider the head of the linked list. When we add a node at the beginning, the newly added node becomes the new head of the list.
Algorithm
Step 1 ? Create the new node
Step 2 ? Add the data in the newly created node
Step 3 ? Update the link of the new node to point to the current head node
Step 4 ? Make the head pointer equal to the newly created node
Note ? The sequence of these steps matters. If you make the newly created node the head first, you will have no way to update its link to point to the previous head node.
Example
class Node:
def __init__(self, data):
self.dataPart = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.headNode = None
def showList(self):
n = self.headNode
while n is not None:
print(n.dataPart, end='-')
n = n.nextNode
print('')
def addBeginList(self, data):
tempNode = Node(data)
tempNode.nextNode = self.headNode
self.headNode = tempNode
# Create and test the linked list
newLinkedList = LinkedList()
print("Printing the list before adding element:")
newLinkedList.showList()
newLinkedList.addBeginList(10)
newLinkedList.addBeginList(25)
print("Printing the elements after adding at the beginning of the list:")
newLinkedList.showList()
Printing the list before adding element: Printing the elements after adding at the beginning of the list: 25-10-
Adding Elements at the End
Adding elements at the end is logically different from adding at the beginning. We need to access the last node of the list instead of the head.
We must check whether the list is empty or already contains elements. If the list is empty (head is None), the new node becomes the first node. Otherwise, we traverse to the end and add the new node there.
Algorithm
Step 1 ? Create a new node
Step 2 ? Add the data in the data part of the node
Step 3 ? Make sure the next node of the newly created node points to None
Step 4 ? If the list is empty, make the newly created node the head node
Step 5 ? Else traverse to the end of list to find the last node
Step 6 ? Set the next node of the last node to the newly created node
Example
class Node:
def __init__(self, data):
self.dataPart = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.headNode = None
def showList(self):
n = self.headNode
while n is not None:
print(n.dataPart, end='-')
n = n.nextNode
print("")
def addEndList(self, data):
tempNode = Node(data)
if self.headNode is None:
self.headNode = tempNode
else:
n = self.headNode
while n.nextNode is not None:
n = n.nextNode
n.nextNode = tempNode
# Create and test the linked list
newLinkedList = LinkedList()
print("Printing the list before insertion:")
newLinkedList.showList()
newLinkedList.addEndList(25)
newLinkedList.addEndList(10)
print("Printing the list after adding elements at the end:")
newLinkedList.showList()
Printing the list before insertion: Printing the list after adding elements at the end: 25-10-
Complete Example with Both Operations
class Node:
def __init__(self, data):
self.dataPart = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.headNode = None
def showList(self):
if self.headNode is None:
print("List is empty")
return
n = self.headNode
while n is not None:
print(n.dataPart, end='-')
n = n.nextNode
print("")
def addBeginList(self, data):
tempNode = Node(data)
tempNode.nextNode = self.headNode
self.headNode = tempNode
def addEndList(self, data):
tempNode = Node(data)
if self.headNode is None:
self.headNode = tempNode
else:
n = self.headNode
while n.nextNode is not None:
n = n.nextNode
n.nextNode = tempNode
# Demonstrate both operations
myList = LinkedList()
print("Initial list:")
myList.showList()
# Add elements at beginning
myList.addBeginList(20)
myList.addBeginList(15)
print("After adding at beginning:")
myList.showList()
# Add elements at end
myList.addEndList(30)
myList.addEndList(40)
print("After adding at end:")
myList.showList()
Initial list: List is empty After adding at beginning: 15-20- After adding at end: 15-20-30-40-
Conclusion
In this article, we discussed how to implement a linked list using Python classes and how to add elements at both the beginning and end positions. Adding at the beginning requires updating the head pointer, while adding at the end requires traversing to the last node first.
