Skip to content

Commit d5901a3

Browse files
add a solution for 206
1 parent 599429f commit d5901a3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/main/java/com/fishercoder/solutions/_206.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,23 @@ ListNode reverse(ListNode head, ListNode newHead) {
3434
}
3535
}
3636

37+
public static class Solution3 {
38+
39+
/**
40+
* I feel like using the variable called prev makes more sense to me on 10/25/2021
41+
* since it's literally a previous node when we start reversing from the head of the list.
42+
* Again, using a pen and paper to visualize the steps helps a lot to convert thoughts into code.
43+
*/
44+
public ListNode reverseList(ListNode head) {
45+
ListNode prev = null;
46+
while (head != null) {
47+
ListNode next = head.next;
48+
head.next = prev;
49+
prev = head;
50+
head = next;
51+
}
52+
return prev;
53+
}
54+
}
55+
3756
}

src/test/java/com/fishercoder/_206Test.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@
1111
public class _206Test {
1212
private static _206.Solution1 solution1;
1313
private static _206.Solution2 solution2;
14+
private static _206.Solution3 solution3;
1415
private static ListNode head;
1516

1617
@BeforeClass
1718
public static void setup() {
1819
solution1 = new _206.Solution1();
1920
solution2 = new _206.Solution2();
21+
solution3 = new _206.Solution3();
2022
}
2123

2224
@Test
@@ -30,4 +32,10 @@ public void test2() {
3032
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4});
3133
assertEquals(LinkedListUtils.contructLinkedList(new int[]{4, 3, 2, 1}), solution2.reverseList(head));
3234
}
35+
36+
@Test
37+
public void test3() {
38+
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4});
39+
assertEquals(LinkedListUtils.contructLinkedList(new int[]{4, 3, 2, 1}), solution3.reverseList(head));
40+
}
3341
}

0 commit comments

Comments
 (0)