Below is a Python implementation of a singly linked list. This program includes the following operations:
Insertion at the beginning, end, and specific position
Deletion from the beginning, end, and specific position
Traversal (printing the list)
Searching for a node
Code
python
class Node:
"""
A class to represent a node in the linked list.
Attributes:
----------
data : any
The data stored in the node.
next : Node
The reference to the next node in the list.
"""
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
"""
A class to represent a linked list.
Attributes:
----------
head : Node
The first node in the linked list.
"""
def __init__(self):
self.head = None
### Insertion Operations
def insert_at_beginning(self, data):
"""
Inserts a new node at the beginning of the linked list.
Parameters:
----------
data : any
The data for the new node.
"""
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_at_end(self, data):
"""
Inserts a new node at the end of the linked list.
Parameters:
----------
data : any
The data for the new node.
"""
if not self.head:
self.head = Node(data)
return
current = self.head
while current.next:
current = current.next
current.next = Node(data)
def insert_at_position(self, data, position):
"""
Inserts a new node at the specified position in the linked list.
Parameters:
----------
data : any
The data for the new node.
position : int
The position where the new node is to be inserted.
"""
if position == 0:
self.insert_at_beginning(data)
return
current = self.head
current_position = 0
while current and current_position < position - 1:
current = current.next
current_position += 1
if not current:
print("Position exceeds the list length. Inserting at the end.")
self.insert_at_end(data)
return
new_node = Node(data)
new_node.next = current.next
current.next = new_node
### Deletion Operations
def delete_from_beginning(self):
"""
Deletes the node at the beginning of the linked list.
Returns:
-------
any
The data of the deleted node, or None if the list is empty.
"""
if self.head:
deleted_data = self.head.data
self.head = self.head.next
return deleted_data
return None
def delete_from_end(self):
"""
Deletes the node at the end of the linked list.
Returns:
-------
any
The data of the deleted node, or None if the list is empty.
"""
if not self.head:
return None
if not self.head.next:
deleted_data = self.head.data
self.head = None
return deleted_data
current = self.head
while current.next.next:
current = current.next
deleted_data = current.next.data
current.next = None
return deleted_data
def delete_from_position(self, position):
"""
Deletes the node at the specified position in the linked list.
Parameters:
----------
position : int
The position of the node to be deleted.
Returns:
-------
any
The data of the deleted node, or None if the position is invalid.
"""
if position == 0:
return self.delete_from_beginning()
current = self.head
current_position = 0
while current and current_position < position - 1:
current = current.next
current_position += 1
if not current or not current.next:
print("Position exceeds the list length.")
return None
deleted_data = current.next.data
current.next = current.next.next
return deleted_data
### Other Operations
def print_list(self):
"""
Prints the elements of the linked list.
"""
current = self.head
while current:
print(current.data, end=" -> " if current.next else "\n")
current = current.next
def search(self, data):
"""
Searches for a node with the specified data in the linked list.
Parameters:
----------
data : any
The data to search for.
Returns:
-------
bool
True if the data is found, False otherwise.
"""
current = self.head
while current:
if current.data == data:
return True
current = current.next
return False
# Example Usage
if __name__ == "__main__":
ll = LinkedList()
# Inserting nodes
ll.insert_at_end(1)
ll.insert_at_end(2)
ll.insert_at_end(3)
print("Linked List after inserting 1, 2, 3 at the end:")
ll.print_list() # Output: 1 -> 2 -> 3
ll.insert_at_beginning(0)
print("Linked List after inserting 0 at the beginning:")
ll.print_list() # Output: 0 -> 1 -> 2 -> 3
ll.insert_at_position(2.5, 3)
print("Linked List after inserting 2.5 at position 3:")
ll.print_list() # Output: 0 -> 1 -> 2 -> 2.5 -> 3
# Deleting nodes
print("Deleted from beginning:", ll.delete_from_beginning())
print("Linked List after deleting from the beginning:")
ll.print_list() # Output: 1 -> 2 -> 2.5 -> 3
print("Deleted from end:", ll.delete_from_end())
print("Linked List after deleting from the end:")
ll.print_list() # Output: 1 -> 2 -> 2.5
print("Deleted from position 1:", ll.delete_from_position(1))
print("Linked List after deleting from position 1:")
ll.print_list() # Output: 1 -> 2.5
# Searching
print("Is 2.5 in the list?", ll.search(2.5)) # Output: True
print("Is 3 in the list?", ll.search(3)) # Output: False
Explanation
We define two classes: Node and LinkedList.
Node represents each element in the linked list. It has two attributes: data to hold the value of the node and next to point to the next node in the sequence.
LinkedList represents the entire list. It has one attribute: head, which points to the first node in the list.
Insertion Methods:
insert_at_beginning(data): Creates a new node with the given data and inserts it at the start of the list by updating the head.
insert_at_end(data): Traverses to the end of the list and appends a new node with the given data.
insert_at_position(data, position): Inserts a new node at the specified position. If the position exceeds the list length, it appends the node at the end.
Deletion Methods:
delete_from_beginning(): Removes the first node and returns its data. If the list is empty, it returns None.
delete_from_end(): Traverses to the second last node, removes the last node, and returns its data.
delete_from_position(position): Deletes the node at the specified position and returns its data. If the position is invalid, it returns None.
Other Methods:
print_list(): Traverses the list and prints the data of each node.
search(data): Looks for a node with the specified data and returns True if found, False otherwise.
Time Complexity
Insertion at beginning: O(1)
Insertion at end: O(n) where n is the number of nodes
Insertion at position: O(n) in the worst case
Deletion from beginning: O(1)
Deletion from end: O(n)
Deletion from position: O(n)
Search: O(n)
Space Complexity
The space complexity is O(n) where n is the number of nodes in the linked list, as each node occupies space in memory.