easylinked-listpointer

Reverse a Linked List

Reverse a singly linked list. Iterative (O(1) extra space) or recursive (O(n) stack).

Problem

Statement

You are given the head of a singly-linked list. Reverse it and print the new head-to-tail sequence.

The iterative solution uses three pointers — prev, curr, next — and walks the list once, rewriting each curr.next to point at prev. O(n) time, O(1) space.

The recursive solution is short but uses O(n) stack; recurse to the end, then unwind rewriting pointers.

For this challenge, take the list as space-separated integers on line 1 and print the reversed sequence.

Worked cases

Examples

Input
1 2 3 4 5
Output
5 4 3 2 1
Input
1 2
Output
2 1
Input
Output
NoteEmpty list stays empty.
Bounds

Constraints

  • 0 ≤ list length ≤ 5000
  • -1000 ≤ node value ≤ 1000
Reference

Sample solutions

Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.

Python
# Iterative reversal — no actual linked list needed for this I/O shape;
# the algorithm shape is preserved: walk once, rebuild in reverse.
vals = input().split()
print(*vals[::-1])
Java
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.hasNextLine() ? sc.nextLine() : "";
        if (line.isBlank()) { System.out.println(""); return; }
        String[] p = line.trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = p.length - 1; i >= 0; i--) { sb.append(p[i]); if (i > 0) sb.append(' '); }
        System.out.println(sb);
    }
}
C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    string line; getline(cin, line);
    vector<string> v; stringstream ss(line); string x; while (ss >> x) v.push_back(x);
    for (int i = (int)v.size() - 1; i >= 0; --i) { cout << v[i]; if (i) cout << ' '; }
    cout << "\n";
}
Also try