Reverse a Linked List
Given the beginning of a singly linked list head, reverse the list, and return the new beginning of the list.
Example 1:
Input: head = [0,1,2,3]
Output: [3,2,1,0]
Example 2:
Input: head = []
Output: []
Constraints:
0 <= The length of the list <= 1000.
-1000 <= Node.val <= 1000
Solution
A Classic problem. All we need to do is maintaining 3 continuous nodes at the same time and reverse the links between.
Code
# 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]:
last, nxt = None, None
cur = head
while cur:
nxt = cur.next
cur.next = last
last = cur
cur = nxt
return last