How to Implement Linked List in Python: Simple Guide
To implement a linked list in Python, create a
Node class to hold data and a reference to the next node, then build a LinkedList class to manage nodes. Use methods to add, remove, or traverse nodes in the list.Syntax
A linked list uses two main parts: a Node class and a LinkedList class.
Nodeholds the data and a pointer to the next node.LinkedListmanages the nodes, starting from the head.- Methods like
appendadd nodes, andprint_listshows all nodes.
python
class Node: def __init__(self, data): self.data = data self.next = None 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 def print_list(self): current = self.head while current: print(current.data, end=' -> ') current = current.next print('None')
Example
This example shows how to create a linked list, add three items, and print them in order.
python
class Node: def __init__(self, data): self.data = data self.next = None 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 def print_list(self): current = self.head while current: print(current.data, end=' -> ') current = current.next print('None') # Create linked list and add items ll = LinkedList() ll.append(10) ll.append(20) ll.append(30) # Print the list ll.print_list()
Output
10 -> 20 -> 30 -> None
Common Pitfalls
Common mistakes when implementing linked lists include:
- Not updating the
nextpointer correctly, causing lost nodes. - Forgetting to handle the empty list case when adding the first node.
- Infinite loops if the
nextpointer never becomesNone.
Always check if the list is empty before adding nodes and ensure the next pointer is set properly.
python
class LinkedList: def __init__(self): self.head = None # Wrong: does not handle empty list def append_wrong(self, data): new_node = Node(data) last = self.head while last.next: last = last.next last.next = new_node # Right: handles empty list def append_right(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
Quick Reference
- Node class: stores data and next pointer.
- LinkedList class: manages nodes starting at head.
- append(data): adds new node at end.
- print_list(): prints all node data in order.
- Always check if list is empty before adding nodes.
Key Takeaways
A linked list uses nodes with data and a pointer to the next node.
Always handle the empty list case when adding the first node.
Traverse nodes by following the next pointers until None is reached.
Incorrect next pointer updates can cause lost nodes or infinite loops.
Use methods in a LinkedList class to organize node operations cleanly.