Lesson 1

Linked List Operations in Python

Lesson Overview

Welcome to our tutorial focusing on Linked List Operations in Python. Singly-Linked Lists (or just Linked Lists) are one of the most fundamental data structures used in computer science. They provide an efficient way to store and access data that is not necessarily contiguous in memory. This ability separates linked lists from arrays, making them an indispensable tool in a programmer's toolkit.

LinkedList Definition

To work with linked lists, we first need to define a ListNode class, which represents a node in the linked list.

Python
1class ListNode: 2 def __init__(self, value=0, next=None): 3 self.value = value # Holds the value or data of the node 4 self.next = next # Points to the next node in the linked list; default is None 5 6# Initialization of linked list 7head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))

In the ListNode class:

  • value holds the data of the node.
  • next is a reference to the next node in the linked list. It is None by default, meaning the node does not point to any other node when it's freshly created.

To understand this, first know that a linked list is a linear data structure where each element is a separate object known as a node. A node comprises data and a reference (link) to the next node in the sequence.

The provided code creates a linked list where each node points to another as follows: 1 -> 2 -> 3 -> 4 -> 5, and the last node points to None.

Task Example

One example of a problem to practice involves reversing a linked list, a common operation in interviews and industry. To reverse a linked list, we'll need to sequentially rearrange the next link of each node to point toward its previous node.

Here is what the code might look like. Note that this code uses O(1)O(1) of additional memory:

Python
1class ListNode: 2 def __init__(self, val=0, next=None): 3 self.val = val 4 self.next = next 5 6def reverse_linked_list(head): 7 prev = None 8 current = head 9 while current: 10 next_node = current.next 11 current.next = prev 12 prev = current 13 current = next_node 14 return prev 15 16# Test 17head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) 18reversed_head = reverse_linked_list(head) 19while reversed_head: 20 print(reversed_head.val, end=" ") 21 reversed_head = reversed_head.next # Output: 5 4 3 2 1
Next: Practice!

I urge you to observe, analyze, and understand the problem and the corresponding solution. This practice will facilitate a well-rounded understanding of linked list operations and their applications. By the end of the tutorial, you should feel more comfortable tackling linked list problems, allowing you to handle similar tasks in technical interviews. Let's get started with practical exercises!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.