206. Reverse Linked List

经典链表操作,也算利用了双指针的思想:

初始化双指针,prevNone(完成reverse后的表尾),curhead(现表头),然后用cur遍历链表:

  1. 用一个临时对象temp暂存cur的下一个nodecur.next

  2. cur的指针指向prev(逆转curprev的指针方向)

  3. prevcur指针分别移动到curtemp(即在原链表顺序上往后移动一格)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        prev = None
        cur = head
        while cur:
            follow = cur.next
            cur.next = prev
            prev = cur
            cur = follow
        return prev

Last updated

Was this helpful?