题目链接:206.反转链表
难度:简单

描述:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

提示:
链表中的结点数是[0, 5000]

题解

思路:
没什么好说的。

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, val=0, next=None):
  4. # self.val = val
  5. # self.next = next
  6. class Solution:
  7. def reverseList(self, head: ListNode) -> ListNode:
  8. prev = None
  9. cur = head
  10. while cur is not None:
  11. temp = cur.next
  12. cur.next = prev
  13. prev = cur
  14. cur = temp
  15. return prev
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, val=0, next=None):
  4. # self.val = val
  5. # self.next = next
  6. class Solution:
  7. def reverseList(self, head: ListNode) -> ListNode:
  8. if head is None or head.next is None:
  9. return head
  10. # 找到最后一个有效节点
  11. ret = self.reverseList(head.next)
  12. head.next.next = head
  13. head.next = None
  14. return ret