打卡题目:leetcode第206题,反转链表
    相似题目:92、234
    image.png


    【思路】
    使用三个指针p、q、r,指向三个相邻的节点,其中p.next为q,q.next为r。
    修改q的指针指向,并且移动p、q、r三个指针,即q.next = p,p = q,q = r,r = r.next。不断循环,并注意修改head.next及head,即可实现链表翻转。


    【代码】

    1. # Definition for singly-linked list.
    2. # class ListNode:
    3. # def __init__(self, x):
    4. # self.val = x
    5. # self.next = None
    6. class Solution:
    7. def reverseList(self, head: ListNode) -> ListNode:
    8. pre = None
    9. cur = head
    10. while cur:
    11. temp = cur.next
    12. cur.next = pre
    13. pre = cur
    14. cur = temp
    15. return pre