使用python实现单链表反转,核心就是当前cur游标和下一个链表节点。
- 初始化当前cur节点和反转链表
- temp临时变量记录下一个节点信息
- 赋值反转链表
- 剩余链表赋值给cur游标
class Node(object):
def __init__(self, x):
self.value = x
self.next = None
def __str__(self):
return str(self.value)
class Solution:
def reverseList(self, head):
cur, prev = head, None
while cur: # 1 2 3 4
temp = cur.next # 2>3>4 3>4 4 None
cur.next = prev # 1 2>1 3>2>1 4>3>2>1
prev = cur # 1 2>1 3>2>1 4>3>2>1
cur = temp # 2>3>4 3>4 4 None
return prev
if __name__ == '__main__':
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
# n5 = Node(5)
# n6 = Node(6)
n1.next = n2
n2.next = n3
n3.next = n4
# n4.next = n5
# n5.next = n6
cc = Solution().reverseList(n1)
print(cc)
print(cc.next)
print(cc.next.next)
print(cc.next.next.next)
# print(cc.next.next.next.next)
# print(cc.next.next.next.next.next)
网友评论