python codekatas solutions | Cell 5 | Cell 7 | Search

The code implements a singly linked list node class (ListNode) and a function (reverse_list) to reversely iterate through the linked list, swapping the next node reference, and returning the new head of the reversed list.

Alternatively, you could also condense it into two sentences:

The ListNode class represents a node in a singly linked list, with methods for initialization, string representation, and equality comparison. The reverse_list function takes the head of a linked list as input and returns the new head of the reversed list, achieved through iterative traversal and node reference swapping.

Cell 6

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
        
    def __str__(self): # for your debugging purposes
        return str(self.val) + '->' + str(self.next)
    
    def __eq__(self, other): # for asserts to work
            return (isinstance(other, self.__class__) 
                and self.__dict__ == other.__dict__)
        
def reverse_list(head):
    """Iterative solution."""
    prev = None
    while head:
        nxt = head.next
        head.next = prev
        prev = head
        head = nxt
    return prev

head = ListNode(1)
rev = ListNode(1)
assert reverse_list(head) == head

head = ListNode(1)
head.next = ListNode(2)
rev = ListNode(2)
rev.next = ListNode(1)
assert reverse_list(head) == rev

head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
rev = ListNode(3)
rev.next = ListNode(2)
rev.next.next = ListNode(1)
assert reverse_list(head) == rev
print('All passed!')

What the code could have been:

python
class ListNode:
    """Represents a node in a singly linked list."""
    
    def __init__(self, val):
        """
        Initializes a ListNode with a value and sets the next node to None.
        
        Args:
            val: The value of the node.
        """
        self.val = val
        self.next = None

    def __str__(self):
        """Returns a string representation of the node for debugging purposes."""
        values = []
        current = self
        while current:
            values.append(str(current.val))
            current = current.next
        return '->'.join(values)

    def __eq__(self, other):
        """
        Checks if two nodes are equal by comparing their values and next nodes.
        
        Args:
            other: The node to compare with.
        
        Returns:
            True if the nodes are equal, False otherwise.
        """
        if not isinstance(other, self.__class__):
            return False
        return self.__dict__ == other.__dict__

def reverse_list(head):
    """
    Reverses a singly linked list iteratively.
    
    Args:
        head: The head of the linked list.
    
    Returns:
        The new head of the reversed linked list.
    """
    prev = None  # prev node in the reversed list
    while head:  # while there are nodes in the list
        nxt = head.next  # store the next node
        head.next = prev  # reverse the link
        prev = head  # move to the next node in the reversed list
        head = nxt  # move to the next node in the original list
    return prev  # return the new head of the reversed list

# Test cases
def test_reverse_list():
    # Test case 1: Linked list with one node
    head = ListNode(1)
    assert reverse_list(head) == head
    
    # Test case 2: Linked list with two nodes
    head = ListNode(1)
    head.next = ListNode(2)
    rev = ListNode(2)
    rev.next = ListNode(1)
    assert reverse_list(head) == rev
    
    # Test case 3: Linked list with three nodes
    head = ListNode(1)
    head.next = ListNode(2)
    head.next.next = ListNode(3)
    rev = ListNode(3)
    rev.next = ListNode(2)
    rev.next.next = ListNode(1)
    assert reverse_list(head) == rev

test_reverse_list()
print('All tests passed!')

Code Breakdown

ListNode Class

This is a Python implementation of a singly linked list node.

__init__ Method

Initializes a new ListNode instance with a given value x and sets the next attribute to None.

__str__ Method

Returns a string representation of the node, including its value and the value of its next node.

__eq__ Method

Compares two ListNode instances for equality. Two nodes are considered equal if they have the same attributes (val and next).

reverse_list Function

Reverses a singly linked list iteratively.

Parameters

Return Value

The new head of the reversed linked list.

Algorithm

  1. Initialize three pointers: prev, head, and nxt.
  2. Traverse the linked list:
  3. Repeat step 2 until the end of the list is reached (head becomes None).
  4. Return the new head of the reversed linked list (prev).

Example Usage

The code includes three test cases to verify the correctness of the reverse_list function. Each test case creates a linked list with a specific structure and checks that the reversed list is correct.