SoFunction
Updated on 2024-11-17

Python implementation of reversing elements in a single linked table

Given a single linked table, reverse it. It's really easy to think of, just change the pointers at each node: i.e., make the latter node point to the former node, and point the table head pointer to the last node.

This process can be implemented with a loop or with recursion.

1. Use a loop to realize it:

class LNode:
    def __init__(self, elem):
         = elem
         = None
 
def reverse(head):
    if head is None or  is None: # If the input table is empty or has only one node, return the current node directly.
        return head
    pre = None # Used to point to the previous node
    cur = newhead = head #cur is the current node. newhead points to the current new head node.
    while cur:
        newhead = cur
        temp = 
         = pre # Point the pointer of the current node to the previous node.
        pre = cur
        cur = temp
    return newhead
 
if __name__=="__main__":
    head = LNode(1)
    p1 = LNode(2)
    p2 = LNode(3)
     = p1
     = p2
    p = reverse(head)
    while p:
        print()
        p = 

2. Use recursion to realize it:

class LNode:
    def __init__(self, elem):
         = elem
         = None
 
def reverse(head):
    if not head or not :
        return head
    else:
        newhead = reverse()
         = head # Make the pointer to the next node point to the current node.
         = None # Disconnect the pointer pointing link between the current node and the next node so that it points to null
        return newhead
 
 
if __name__=="__main__":
    head = LNode(1)
    p1 = LNode(2)
    p2 = LNode(3)
     = p1
     = p2
    p = reverse(head)
    while p:
        print()
        p = 

Below is the detailed procedure for graphical recursion:

This is the whole content of this article.