-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_206.java
More file actions
35 lines (28 loc) · 819 Bytes
/
Copy pathP_206.java
File metadata and controls
35 lines (28 loc) · 819 Bytes
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
package leetcode.easy;
import utils.DataStructures.ListNode;
@SuppressWarnings({ "ConstantConditions", "TailRecursion" })
public class P_206 {
// Iterative
public ListNode reverseListIterative(ListNode head) {
ListNode newHead = null;
while (head != null) {
final ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
// Recursive
public ListNode reverseList(ListNode list) {
return reverse(list, null);
}
private static ListNode reverse(ListNode list, ListNode newHead) {
if (list == null) {
return newHead;
}
final ListNode next = list.next;
list.next = newHead;
return reverse(next, list);
}
}