forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_206.java
56 lines (48 loc) · 1.56 KB
/
_206.java
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
55
56
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
public class _206 {
public static class Solution1 {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
public static class Solution2 {
public ListNode reverseList(ListNode head) {
return reverse(head, null);
}
ListNode reverse(ListNode head, ListNode newHead) {
if (head == null) {
return newHead;
}
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
return reverse(head, newHead);
}
}
public static class Solution3 {
/**
* I feel like using the variable called prev makes more sense to me on 10/25/2021
* since it's literally a previous node when we start reversing from the head of the list.
* Again, using a pen and paper to visualize the steps helps a lot to convert thoughts into code.
*/
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
}