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.
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!')
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!')
This is a Python implementation of a singly linked list node.
__init__
MethodInitializes a new ListNode instance with a given value x
and sets the next
attribute to None
.
__str__
MethodReturns a string representation of the node, including its value and the value of its next
node.
__eq__
MethodCompares two ListNode instances for equality. Two nodes are considered equal if they have the same attributes (val
and next
).
reverse_list
FunctionReverses a singly linked list iteratively.
head
: The head of the linked list to reverse.The new head of the reversed linked list.
prev
, head
, and nxt
.nxt
to the next node in the list (head.next
).head.next
to prev
, effectively reversing the link between the current node and its next node.prev
and head
one step forward.head
becomes None
).prev
).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.