Talentd
FleetCode

206. Reverse Linked List

Easy81.0% acceptance34 companies

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: []

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

11:07
Still stuck?Read 4 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for singly-linked list.
2# class ListNode:
3# def __init__(self, val=0, next=None):
4# self.val = val
5# self.next = next
6class Solution:
7 def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
8
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3,4,5]
Input
[1,2]
Input
[]
Your code is saved on this device.Solution