Singly Linked List
Singly linked list in Python
A singly linked list in Python is a linear data structure where each element (node) points to the next element in the sequence. Each node consists of two parts:
data:
stores the actual value.next:
points to the next node in the list (or None if it is the last node).
Here’s an example of using a singly linked list in Python.
Output
Explanation
This code defines a singly linked list with three basic operations:
- Appending a Node
(append)
– Adds a new node at the end. - Deleting a Node
(delete)
– Removes a node by its value. - Displaying the List
(display)
– Prints the list in order.
1. Node Class (Node)
Each node in the linked list contains:
data
→ The value stored in the node.next
→ A pointer to the next node in the list.
- When a
Node
object is created, itsdata
is set, andnext
isNone
(meaning no next node yet).
2. LinkedList Class (LinkedList)
This class manages the linked list operations.
(a) Initializing the Linked List:
self.head
stores the first node of the linked list.- If
head
isNone
, the list is empty.
(b) Append a Node (append)
Adds a new node to the end of the list.
- If
head
isNone
, the list is empty, so we sethead = Node(data)
. - Otherwise, we traverse (
while current.next
) until we reach the last node. - Then, we create a new node and attach it to the last node.
(c) Delete a Node (delete)
Removes a node containing a specific value.
- If the list is empty, nothing happens.
- If the node to delete is the
head
, movehead
to the next node. - Otherwise, we traverse to find the node before the one to be deleted.
- If found, we adjust the
next
pointer to skip the unwanted node.
(d) Display the List (display)
Prints all nodes in order.
- Starts at
head
and prints each node’sdata
. - Stops when
current
becomesNone
.