leetcode-反转链表

206. 反转链表

题解:

定义两个指针prev和cur,分别指向当前节点的前一个节点和当前节点,初始时,prev为None,cur为head,在遍历的过程中,我们需要创建一个临时指针用来指向cur.next,因为cur指向prev之后,就会和cur.next断链了。遍历过程是,每次将cur的next指针执行prev,然后将prev和cur分别向后移动一位,当遍历到尾部时,链表就被反转了,反转后的链表头节点是prev.

# 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: Optional[ListNode]) -> Optional[ListNode]:
        prev = None
        cur = head

        while cur:
            tmp = cur.next
            cur.next = prev
            prev = cur
            cur = tmp
        return prev

你可能感兴趣的:(leetcode)