# LeetCode Reverse Linked List: Recursive VS Iterative Solution

## Overview

LeetCode Reverse Linked List: Recursive solution takes O(N) time and O(N) space while Iterative Solution takes O(N) time and O(1) space.

## LeetCode Reverse Linked List

Reverse a singly linked list. Can you solve it both recursively and iteratively?

## LeetCode Reverse Linked List Recursive and Iterative Solution

LeetCode Reverse Linked List: Recursive solution takes O(N) time and O(N) space while Iterative Solution takes O(N) time and O(1) space. And the following Java code could be accepted by LeetCode OJ to solve this Reverse Linked List problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
int x = (Math.random() < 0.5) ? 0 : 1;
if (x == 0) {
return reverseListIteratively(head);
} else {
return reverseListRecursively(head);
}
}
private ListNode reverseListIteratively(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p1 = head, p2 = head.next, p3;
p1.next = null;
while (p2 != null) {
p3 = p2.next;
p2.next = p1;
p1 = p2;
p2 = p3;
}
return p1;
}
private ListNode reverseListRecursively(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p1 = head.next;
ListNode p2 = reverseListRecursively(p1);
head.next = null;
p1.next = head;
return p2;
}
}

**Note: **

- be careful about the recursive solution in case of StackOverFlow Exception, and another observation is that the first node and the last node of the reversed linked list is known directly, right?
- Also take a look at this generalized problem to reverse a linked list from position m to n: LeetCode Reverse Linked List II: One Pass

## Summary

LeetCode Reverse Linked List: Recursive solution takes O(N) time and O(N) space while Iterative Solution takes O(N) time and O(1) space.

Written on July 12, 2015