πŸ”—206. Reverse Linked List

Easy | Grind 75 | November 6th Saturday, 2022

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

Constraints:

  • The number of nodes in the list is the range [0, 5000].

  • -5000 <= Node.val <= 5000

SOLUTION

We set a variable tail which will be the head of the reversed linked list. Initially, it is set to null because the head of the original linked list should point to null. We will now iterate through the original linked list, and for each node, change the next pointer of the head to point to the tail node. Then change the head to head.next and tail to head. We repeat this until the head points to null and return the tail node which will be the head of the reverse linked list.

TIME AND SPACE COMPLEXITY

TIME: O(n) where n is the length of the linked list. We have to iterate over all the nodes once.

SPACE: O(1) we only need two variables regardless of the length of the linked list.

Last updated