A Singly Linked List is a data structure where each element (or node) contains two parts:
Data: The value of the node.
Next: A pointer/reference to the next node in the list.
class LinkedList:
def __init__(self):
self.head = None # The head (start) of the list
# Function to insert a new node at the end of the list
def append(self, data):
new_node = Node(data)
if self.head is None: # If the list is empty, the new node becomes the head
self.head = new_node
return
last_node = self.head
while last_node.next: # Traverse to the last node
last_node = last_node.next
last_node.next = new_node # Link the last node to the new node
# Function to display the linked list
def display(self):
current_node = self.head
while current_node:
print(current_node.data, end=" -> ")
current_node = current_node.next
print("None") # End of list
# Create a new Linked List and append elements
llist = LinkedList()
llist.append(10)
llist.append(20)
llist.append(30)
llist.append(40)
# Display the linked list
llist.display()