This article introduces python how to realize the inversion of a single linked table, the text of the sample code through the introduction of the very detailed, for everyone's learning or work has a certain reference learning value, you can refer to the next!
The code is as follows
# coding=utf-8 class Node: def __init__(self, data=None, next=None): = data = next def Reserver(link): pre = link cur = = None while cur: tmp = = pre pre = cur cur = tmp return pre if __name__ == "__main__": node = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9))))))))) root = Reserver(node) while root: print , root =
Explain the implementation of the rev function:
lines 9-11 are turning the first node of the original chain table into the last node of the new chain table, while keeping the second node of the original chain table in cur
lines13-16 are traversed from the second node to the last node of the original chain table, flipping all nodes once
Take the example of flipping the second node
temp = is to save the next node of cur in temp, that is, node 3, because after the flip, the next node of node 2 becomes node 1, and the connection between node 2 and node 3 is disconnected, so you can't find node 3 through node 2, so you need to save it.
= pre is pointing the next node of node 2 to node 1
Then pre moves backward to the original position of cur, and cur moves backward one node, i.e., pre = cur ,cur =temp
This sets the stage for flipping node 3
This is the entire content of this article.