Wednesday, February 21, 2024
HomeSoftware EngineeringEasy methods to Reverse a singly-linked record in Python

Easy methods to Reverse a singly-linked record in Python

The problem

Implement a operate reverse_list that takes a singly-linked record of nodes and returns an identical record within the reverse order.

Assume the presence of a category Node, which exposes the property worth/Worth and subsequent/Subsequentsubsequent should both be set to the subsequent Node within the record, or to None (or null) to point the top of the record.

To help in writing assessments, a operate make_linked_list (Node.asLinkedList() in Java) has additionally been outlined, which converts a python record to a linked record of Node.

The ultimate assessments will use a really lengthy record. Bear in mind {that a} recursive resolution will run out of stack.

The answer in Python code

Possibility 1:

def reverse_list(node):
    res = None
    whereas node:
        res = Node(node.worth, res)
        node = node.subsequent
    return res

Possibility 2:

def reverse_list(head):
    tail = None
    whereas head:
        tail, head.subsequent, head = head, tail, head.subsequent
    return tail

Possibility 3:

def reverse_list(node):
    earlier = None
    whereas node:
        earlier, node, earlier.subsequent = node, node.subsequent, earlier
    return earlier

Check circumstances to validate our resolution

# create linked lists for testing by chaining nodes
take a look at.assert_equals(reverse_list(Node(1, Node(2, Node(3, None)))), Node(3, Node(2, Node(1, None))))
# or alternately use the helper operate
take a look at.assert_equals(reverse_list(make_linked_list([1, 2, 3, 4, 5])), make_linked_list([5, 4, 3, 2, 1]))


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments