How to reverse the elements in a single linked list by Python
This article mainly introduces Python how to achieve the inversion of elements in a single-linked list related knowledge, detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that everyone reading this Python how to achieve the inversion of elements in a single-linked list article will have some gains, let's take a look at it.
Given a single-stranded list, invert it. In fact, it is easy to think that you only need to change the pointer to each node: that is, the next node points to the previous node, and the header pointer points to the last node.
This process can be implemented in a loop or recursively.
1. Use the loop to achieve:
class LNode: def __init__(self, elem): self.elem = elem self.pnext = None def reverse(head): if head is None or head.pnext is None: #If the input list 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 = cur.pnext cur.pnext = pre #Pointer 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) head.pnext = p1 p1.pnext = p2 p = reverse(head) while p: print(p.elem) p = p.pnext
2. Use recursion to implement:
class LNode: def __init__(self, elem): self.elem = elem self.pnext = None def reverse(head): if not head or not head.pnext: return head else: newhead = reverse(head.pnext) head.pnext.pnext = head #Pointer to next node to current node head.pnext = None #Disconnects the pointer between the current node and the next node, making it point to null return newhead if __name__=="__main__": head = LNode(1) p1 = LNode(2) p2 = LNode(3) head.pnext = p1 p1.pnext = p2 p = reverse(head) while p: print(p.elem) p = p.pnext
The following is a detailed illustration of recursion:
About "Python how to achieve the inversion of elements in a single-linked list" The content of this article is introduced here, thank you for reading! I believe everyone has a certain understanding of the knowledge of "Python how to realize the inversion of elements in single-linked lists." If you still want to learn more knowledge, please pay attention to the industry information channel.