Linked Lists in Python
A Linked List is a linear data structure where elements (nodes) are connected using pointers.
Each node contains data and a reference (link) to the next node in the sequence.
Unlike arrays, linked lists do not store elements in contiguous memory locations.
1. Node Structure
A node typically contains two parts:
- Data: The actual value.
- Next: Reference to the next node.
Example:
class Node:
def __init__(self, data):
self.data = data
self.next = None
2. Creating a Linked List
Example:
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
3. Traversing a Linked List
Example:
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
4. Types of Linked Lists
- Singly Linked List: Nodes have a link to the next node only.
- Doubly Linked List: Nodes have links to both the next and previous nodes.
- Circular Linked List: Last node points back to the first node.
5. Advantages & Disadvantages
Advantages:
- Dynamic size
- Efficient insertions/deletions
Disadvantages:
- No random access
- Extra memory for storing pointers