提交 1a05b946 编写于 作者: 檀越@新空间's avatar 檀越@新空间 🐭

fix:反转链表

上级 422cb837
"""
反转链表
"""
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""
反转链表:定义前节点和当前节点
:param head:
:return:
"""
pre, curr = None, head
while curr is not None:
next = curr.next
curr.next = pre
pre = curr
curr = next
return pre
if __name__ == '__main__':
# 1, 2, 6, 3, 4, 5, 6
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(3)
l1.next.next.next = ListNode(4)
l1.next.next.next.next = ListNode(5)
# l1.next.next.next.next.next = ListNode(7)
# l1.next.next.next.next.next.next = ListNode(7)
# l2 = ListNode(5)
# l2.next = ListNode(6)
# l2.next.next = ListNode(1)
# l2.next.next.next = ListNode(8)
# l2.next.next.next.next = ListNode(4)
# l2.next.next.next.next.next = ListNode(5)
result = Solution().reverseList(l1)
while result:
print(result.val, end=' -> ')
result = result.next
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册