LeetCode 0206. Reverse Linked List Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0206. Reverse Linked List

Description

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?

Solutions

Solution 1: Head Insertion Method

We create a dummy node dummy, then traverse the linked list and insert each node after the dummy node. After traversal, return dummy.next.

The time complexity is O(n), where n is the length of the linked list. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptC#
# 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: dummy = ListNode() curr = head while curr: next = curr.next curr.next = dummy.next dummy.next = curr curr = next return dummy.next(code-box)

Solution 2: Recursion

We recursively reverse all nodes from the second node to the end of the list, then attach the head to the end of the reversed list.

The time complexity is O(n), and the space complexity is O(n). Where n is the length of the linked list.

PythonJavaC++GoTypeScriptRustC#
# 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: if head is None or head.next is None: return head ans = self.reverseList(head.next) head.next.next = head head.next = None return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !