Reverse Linked List LeetCode Solution

Here, We see Reverse Linked List problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Reverse Linked List LeetCode Solution

Reverse Linked List LeetCode Solution

Problem Statement ->

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

Reverse Linked List example_1
fig-1
Example 1: (fig-1)
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
fig-2
Example 2: (fig-2)
Input: head = [1,2]
Output: [2,1]

Example 3:
Input: head = []
Output: []

Reverse Linked List Leetcode Solution 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; } };
Code language: C++ (cpp)

Reverse Linked List Leetcode Solution Java ->

class Solution { public ListNode reverseList(ListNode head) { if(head==null || head.next==null) return head; ListNode nextNode=head.next; ListNode newHead=reverseList(nextNode); nextNode.next=head; head.next=null; return newHead; } }
Code language: Java (java)

Reverse Linked List Leetcode Solution JavaScript ->

var reverseList = function(head) { let [prev, current] = [null, head] while(current) { [current.next, prev, current] = [prev, current, current.next] } return prev };
Code language: JavaScript (javascript)

Reverse Linked List Leetcode Solution Python ->

class Solution(object): def reverseList(self, head): prev = None curr = head while curr: next = curr.next curr.next = prev prev = curr curr = next return prev
Code language: Python (python)