206 Reverse Linked List

1. Question

Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

2. Implementation

(1) Iterative
1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
public ListNode reverseList(ListNode head) {
11
ListNode preNode = null, curNode = head, nextNode = null;
12
13
while (curNode != null) {
14
nextNode = curNode.next;
15
curNode.next = preNode;
16
preNode = curNode;
17
curNode = nextNode;
18
}
19
return preNode;
20
}
21
}
Copied!

3. Time & Space Complexity

Iterative: 时间复杂度O(n), 空间复杂度O(1)