Skip to main content
Practice

Dynamically Connecting Data with Linked Lists

Linked Lists are a type of data structure that stores data in a sequential manner where each element contains a reference (pointer) to the next element.

Linked lists have the advantage of not requiring the elements to be in contiguous physical locations and can dynamically adjust their size.


How Are Linked Lists Structured?

Linked lists are composed of units called nodes.

Each node consists of data and a reference (next) to the next node.

In a linked list, the first node is called the head, and since the last node has no reference to a next node, it points to None.


Implementing a Linked List in Python

A linked list is structured such that each node is connected to the next node through the reference.

Below is an example of implementing a linked list in Python.

Example Implementation of a Simple Linked List
# Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None

# Linked List class
class LinkedList:
# Initialize the linked list
def __init__(self):
self.head = None

# Add a node
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
print(f"{data} has been added as the head node.")
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
print(f"{data} has been added to the list.")

# Display the linked list
def display(self):
current_node = self.head
while current_node:
print(current_node.data, end=" -> ")
current_node = current_node.next
print("None")

# Example usage of the linked list
my_list = LinkedList()
my_list.append(1) # 1 has been added as the head node
my_list.append(2) # 2 has been added to the list
my_list.append(3) # 3 has been added to the list

my_list.display() # 1 -> 2 -> 3 -> None

Explanation of the Code

  1. Node class: A node class that contains data and a reference to the next node.

  2. LinkedList class: A class that implements the linked list, with a method append() to add nodes and a method display() to print the list.

  3. append(): A method to add a new node. If the list is empty, it adds the node as the head. Otherwise, it adds the node after the last node.

  4. display(): A method to print the linked list by traversing from the head node to the last node, printing the data.

  5. my_list: An instance of the LinkedList class. It adds 1, 2, and 3 using the append() method and then prints the list using the display() method.

When Are Linked Lists Used?

Linked lists are useful when there are frequent insertions and deletions of data.

For example, they are used in scenarios such as music player playlists that often change or memory management in operating systems where linked lists are utilized.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.