Reverse Linked List – Leetcode Solution

In this post, we are going to solve the 206. Reverse Linked List problem of Leetcode. This problem 206. Reverse Linked List is a Leetcode easy level problem. Let’s see the code, 206. Reverse Linked List – Leetcode Solution.

Problem

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 in the range [0, 5000].
  • -5000 <= Node.val <= 5000

Now, let’s see the code of 206. Reverse Linked List – Leetcode Solution.

Reverse Linked List – Leetcode Solution

206. Reverse Linked List – Solution in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode curr = head, prev = null;
        
        while(curr != null){
            ListNode forw = curr.next;
            curr.next = prev;
            prev = curr;
            curr = forw;
        }
        return prev;
    }
}

206. Reverse Linked List – Solution in C++

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = new ListNode(0), *cur = head;
        pre -> next = head;
        while (cur && cur -> next) {
            ListNode* temp = pre -> next;
            pre -> next = cur -> next;
            cur -> next = cur -> next -> next;
            pre -> next -> next = temp;
        }
        return pre -> next;
    }
};

206. Reverse Linked List – Solution in Python

def reverseList(self, head):
    prev = None
    curr = head

    while curr:
        next = curr.next
        curr.next = prev
        prev = curr
        curr = next
    
    return prev

Note: This problem 206. Reverse Linked List is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *