Algo-Sim › Linked Lists

Reverse Linked List

Easy · Linked Lists · step through it in Java, Python and C++ on your own input

Reverse a singly linked list in place by flipping each next pointer, with prev, curr and next.

Problem

Given the head of a singly linked list, reverse the list in place and return the new head.

Constraints

Edge cases to test

Follow-up questions

Can you reverse only positions left..right?
Walk to node left − 1 and reverse the next right − left + 1 nodes, reconnecting both ends (LC 92): O(n), one pass.
Iterative or recursive?
Iterative uses O(1) space; recursion is shorter but uses O(n) stack and can overflow on long lists.

Solution

Java

public ListNode reverseList(ListNode head) {
    ListNode prev = null, curr = head;
    while (curr != null) {
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

Python

def reverse_list(head):
    prev, curr = None, head
    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    return prev

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *reverseList(ListNode *head) {
        ListNode *prev = nullptr, *curr = head;
        while (curr != nullptr) {
            ListNode *next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
};

More Linked Lists problems