文章

206-reverse-linked-list

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2:

Input: head = [1,2] Output: [2,1] Example 3:

Input: head = [] Output: []

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        if not head:
            return head
        # use two temporary variable
        pre, curr = None, head
        while curr:
            # tmp to store the node not use
            tmp = curr.next
            curr.next = pre
            pre = curr
            curr = tmp
        return pre
本文由作者按照 CC BY 4.0 进行授权