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 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++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* prev = NULL;
        ListNode* cur = head;
        ListNode* nxt = NULL;
        if(head==NULL)return head;
        while(cur!=NULL){
            nxt = cur->next;
            cur -> next = prev;
             prev = cur;
            cur = nxt;
        }
        return prev;
    }
};

206. Reverse Linked List – Solution in Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
       def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur, prev = head, None
        while cur:
            cur.next, prev, cur = prev, cur, cur.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 *