This article is another part of a series on leet code problems solutions, and it provides a solution to the leet code problem number 206. This is a Leet code problem named Reverse Linked List. We will solve it using python and it is the best space and time-optimized solution.
Question of Reverse Linked List
Given the head
of a singly linked list, reverse the list, and return the reversed list.
In this question, we have to reverse the given linked list. Suppose we have a linked list like the below:
1->2->3->4->5
In the above linked list head node is 1 and the tail node is 5. So we simply have to reverse that and after reversing our head node will be 5 and tail node will be 1. It will look like this:
5->4->3->2->1
Example
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
Recursive Approach to solve Reverse Linked List
To solve this question we will solve it using the recursive method. In the recursive approach, we will call the same function. First, we separate the list into two sections: the initial node and the remaining linked list. After that For the remaining connected list items, we call the reverse function again. We will repeat this until we reach the end of the node. Then while backtracing the remainder is connected to the beginning. And we fix the head pointer.
So while doing this our list will be reversed and new head will be last node which we wanted.
Algorithm
This method performs the following steps for a given input array:
- Check the base condition i.e. if the head is Nonne then return the head.
- Now we reverse the rest of the list i.e. calling step 2 for the remaining list.
- Now we put the first element at the end.
- Assign Next of next of head to head
- Assign next of head to None
- Return the rest pointer.
Python Code to Reverse Linked List
# 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]:
#Check the base condition i.e. if the head is Nonne then return the head
if head is None or head.next is None:
return head
# Reverse the rest list
rest = self.reverseList(head.next)
# Put the first element at the end
head.next.next = head
head.next = None
# Fix the header pointer
return rest
Iterative Approach to solve Reverse Linked List
In an iterative approach, we will iterate through the whole linked list. While iterating we will swap the next of the current node.
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
#to store head of previous node
prev = None
#current node while traversing
cur = head
#iterate in linked list
while cur:
#assign nxt to next of current
nxt = cur.next
#assign next of current to previous
cur.next = prev
#assign previous to current
prev = cur
#assign current to next
cur = nxt
return prev
Complexity Analysis
Time Complexity: O(n)
As we traverse the whole list once.
So here is the end of the post. If you find any issues or any questions then write a comment. Share with your friends.
Related Posts:
- Find Pivot Index (Leet Code-724)
- Spiral Matrix Problem Solution
- Isomorphic Strings
- Two Sum IV - Input is a BST (Leet Code-653)
- Search in a Binary Search Tree (Leet Code-700)
- Invert Binary Tree (Leet Code-266)
- Symmetric Tree (Leet Code-101)
- Maximum Depth of Binary Tree (Leet Code-104)
- Binary Tree Postorder Traversal (Leet Code-145)
- Binary Tree Inorder Traversal (Leet Code - 94)
- Binary Tree Pre-Order Traversal
- Binary Tree Level Order Traversal (Leet Code-102)
- Valid Parentheses (Leet Code-20)
- Remove Duplicates from Sorted List (Leet Code-83)
- Remove Linked List Elements (Leet Code-203)
- Merge Two Sorted Lists (Leet code-21)
- Ransom Note (Leet code-383)
- First Unique Character in a String (Leet code-387)
- Valid Sudoku (Leet Code-36)
- Search a 2D Matrix (Leet Code-74)
- Linked List Cycle (Leet Code-141)
- Pascal's Triangle (Leet Code - 118)
- Reshape the Matrix (Leet Code-566)
- Best Time to Buy and Sell Stock (Leet code-121)
- The Intersection of Two Arrays II (Leet Code)
- Binary Search - Leet Code
- Two Sum - Leet Code