Reverse a singly linked list. Iterative (O(1) extra space) or recursive (O(n) stack).
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.
1 2 3 4 5
5 4 3 2 1
1 2
2 1
Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.
# 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])
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);
}
}
#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";
}