class Node:
def __init__(self, value, p=None):
self.data = value
self.next = p
class Solution:
def reverse_link(self, head):
pre = None
cur = head
while cur: #维护三个变量,循环地把当前节点next指向前一个节点
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre # pre始终指向cur的前一个节点,当cur指向None的时候,pre刚好指向原链表的最后一个节点
if __name__ == '__main__':
l = Node(1, Node(2, Node(3, Node(4)))); #构造一个链表1->2->3->4->None
s = Solution()
m = s.reverse_link(l)
while m:
print(m.data)
m = m.next
print(m) #输出链表 4->3->2->1->None
网友评论