Reverse of one way linked list based on Python

Cycle method

The idea of the loop method is to establish three variables, pointing to the current node, the previous node of the current node, and the new head node. Starting from the head, each loop reverses the direction of the two adjacent nodes. After the whole chain list is traversed, the direction of the chain list is reversed.


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


def reverse(head):  # The method of loop reverses the linked list
    if head is None or head.next is None:
        return head
    # Define the initial state of the reversal
    pre = None
    cur = head
    newhead = head
    while cur:
        newhead = cur
        tmp = cur.next
        cur.next = pre
        pre = cur
        cur = tmp
    return newhead

if __name__ == '__main__':
    head = ListNode(1)  # Test code
    p1 = ListNode(2)  # Set up the linked list 1 - > 2 - > 3 - > 4 - > none;
    p2 = ListNode(3)
    p3 = ListNode(4)
    head.next = p1
    p1.next = p2
    p2.next = p3
    p = reverse(head)  # Output list 4 - > 3 - > 2 - > 1 - > none
    while p:
        print(p.val)
        p = p.next

Recursive Method

According to the concept of recursion, we only need to pay attention to the base case condition of recursion, that is, the exit of recursion or the termination condition of recursion, as well as the relationship between the linked list with length N and the linked list with length n-1
The reverse result of the n-1 chain list only needs to reverse the n-1 chain list, change the last point of the chain list to the head of the n chain list, and make the head point to None (or add the head node of the n chain list between the chain list and None)
That is, to reverse the n-1 list, first reverse the n-1 list, and then operate to reverse the relationship between the good list and the head node. As for how to reverse the n-1 length list, just split it into the node1 and n-2 list


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


def reverse(head, newhead):  # Recursion, head is the head node of the original linked list, and newhead is the head node of the inverted linked list
    if head is None:
        return
    if head.next is None:
        newhead = head
    else:
        newhead = reverse(head.next, newhead)
        head.next.next = head
        head.next = None
    return newhead

if __name__ == '__main__':
    head = ListNode(1)  # Test code
    p1 = ListNode(2)  # Create a linked list 1 - > 2 - > 3 - > 4 - > none
    p2 = ListNode(3)
    p3 = ListNode(4)
    head.next = p1
    p1.next = p2
    p2.next = p3
    newhead = None
    p = reverse(head, newhead)  # Output list 4 - > 3 - > 2 - > 1 - > none
    while p:
        print(p.val)
        p = p.next

Posted by MajusC00L on Sun, 03 Nov 2019 14:48:41 -0800