Table of Contents
- Introduction
- Prerequisites
- Setting Up Python
- What is a Linked List?
- Implementing a Linked List
- Linked List Operations
- Conclusion
Introduction
Welcome to this tutorial on implementing a Linked List in Python. A linked list is a data structure that consists of a sequence of nodes, each containing a value and a pointer/reference to the next node. By the end of this tutorial, you will understand what a linked list is, how to create and manipulate it in Python, and the operations you can perform on a linked list.
Prerequisites
To follow this tutorial, you should have a basic understanding of Python programming language and familiarity with object-oriented programming concepts. If you are new to Python, it is recommended to go through some beginner-level Python tutorials first.
Setting Up Python
Before we start, make sure you have Python installed on your system. You can download and install the latest version of Python from the official website (https://www.python.org). Follow the installation instructions provided for your operating system.
What is a Linked List?
A linked list is a linear data structure where each element, called a node, contains a value and a reference to the next node. Unlike arrays or lists, linked lists do not require contiguous memory allocation. Instead, each node can be stored at any memory location, and the references between nodes create the connection.
The first node in the linked list is called the head, and the last node points to null, indicating the end of the list. Linked lists offer flexibility in terms of insertion and deletion of nodes but have slower access times compared to arrays or lists.
Implementing a Linked List
Let’s start by implementing a basic linked list class in Python. Open your favorite text editor or integrated development environment (IDE) and create a new Python file. Save it as linked_list.py
.
```python
class Node:
def init(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
``` In the above code, we define two classes: `Node` and `LinkedList`. The `Node` class represents a single node in the linked list, while the `LinkedList` class represents the entire list. Each node has two properties: `data` to store the value and `next` to store the reference to the next node.
Next, let’s implement a method to insert a new node at the beginning of the linked list.
python
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
The insert
method creates a new node with the given data
and checks if the list is empty. If the list is empty, the new node becomes the head of the list. Otherwise, the next
reference of the new node is set to the current head, and the head is updated to the new node.
To test the linked list implementation, let’s add a method to display the list.
python
def display(self):
current = self.head
while current is not None:
print(current.data, end=" -> ")
current = current.next
print("None")
The display
method iterates through each node starting from the head and prints its data. It continues until it reaches the end of the list, i.e., when current
becomes None
.
Now, let’s create an instance of the LinkedList
class, insert some nodes, and display the list.
python
linked_list = LinkedList()
linked_list.insert(3)
linked_list.insert(7)
linked_list.insert(1)
linked_list.display()
When you run the code, you should see the following output.
1 -> 7 -> 3 -> None
Congratulations! You have implemented a basic linked list in Python. In the next section, we will explore the operations that can be performed on a linked list.
Linked List Operations
Appending a Node
To append a node at the end of the linked list, we need to iterate through the list until we find the last node.
python
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
The append
method creates a new node with the given data
and checks if the list is empty. If the list is empty, the new node becomes the head of the list. Otherwise, it iterates through the list until it finds the last node (when current.next
is None
) and appends the new node.
Inserting a Node at a Specific Position
To insert a node at a specific position, we need to find the position and adjust the references accordingly.
python
def insert_at_position(self, data, position):
if position == 0:
self.insert(data)
else:
new_node = Node(data)
current = self.head
count = 0
while count < position - 1 and current.next is not None:
current = current.next
count += 1
new_node.next = current.next
current.next = new_node
The insert_at_position
method first handles the special case when the position is 0, i.e., inserting at the beginning of the list. For other positions, it creates a new node, iterates through the list until it reaches the desired position or the end of the list, and adjusts the references to insert the new node.
Deleting a Node
To delete a node, we need to find the node and adjust the references of the previous and next nodes.
python
def delete(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
else:
current = self.head
while current.next is not None:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
The delete
method first checks if the list is empty. If not, it handles the special case when the node to be deleted is the head. Otherwise, it iterates through the list until it finds the node or the end of the list. If the node is found, it adjusts the references to skip the node and delete it.
Searching for a Node
To search for a node with a specific value, we can iterate through the list and compare the data.
python
def search(self, data):
current = self.head
while current is not None:
if current.data == data:
return True
current = current.next
return False
The search
method iterates through the list and checks if the current node’s data matches the given value. If found, it returns True
; otherwise, it continues to the next node. If the end of the list is reached without finding the value, it returns False
.
Conclusion
In this tutorial, you have learned how to implement a linked list in Python. We started with an overview of linked lists, their advantages, and their basic structure. Then, we implemented a linked list class and performed various operations such as inserting, appending, deleting, and searching for nodes.
Linked lists are an important data structure with a wide range of applications. They provide a dynamic way of storing and organizing data. By understanding linked lists, you will be better equipped to solve complex programming problems that require efficient memory management and data manipulation.
Now that you have a good grasp of linked lists, don’t hesitate to practice and explore more advanced topics and algorithms related to this data structure. Happy coding!
If you have any questions or need further assistance, feel free to ask in the comments section.