Singly Linked List
A singly linked list is a linear data structure consisting of a sequence of nodes, where each node stores a data element and a reference (link) to the next node in the list. The first node is called the head, and the last node's reference points to null, indicating the end of the list.
Implementation
To implement a singly linked list, we can define two classes: Node
and SinglyLinkedList
.
The Node
class represents each individual node in the list. It has two properties: data
to store the actual data, and next
to store the reference to the next node.
The SinglyLinkedList
class represents the entire linked list. It has one property: head
to store the reference to the first node in the list. It also has methods to insert elements at the end of the list (insert_at_end
) and display the list (display
).
Here is an example of a singly linked list implementation in Python:
1# Singly Linked List Implementation in Python
2
3class Node:
4 def __init__(self, data):
5 self.data = data
6 self.next = None
7
8
9class SinglyLinkedList:
10 def __init__(self):
11 self.head = None
12
13 def insert_at_end(self, data):
14 new_node = Node(data)
15 if self.head is None:
16 self.head = new_node
17 else:
18 current = self.head
19 while current.next:
20 current = current.next
21 current.next = new_node
22
23 def display(self):
24 if self.head is None:
25 print('The list is empty')
26 else:
27 current = self.head
28 while current is not None:
29 print(current.data, '->', end=' ') if current.next else print(current.data)
30 current = current.next
31
32
33# Create a singly linked list
34linked_list = SinglyLinkedList()
35
36# Insert elements
37linked_list.insert_at_end(10)
38linked_list.insert_at_end(20)
39linked_list.insert_at_end(30)
40
41# Display the linked list
42linked_list.display()
Remember to always ensure that the next
of the last node is None
to indicate the end of the list.
xxxxxxxxxx
linked_list.display()
# Singly Linked List Implementation in Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def insert_at_end(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def display(self):
if self.head is None:
print('The list is empty')
else:
current = self.head
while current is not None:
print(current.data, '->', end=' ') if current.next else print(current.data)