Skip to content

Commit 9e718d1

Browse files
refactor 206
1 parent 58bcf77 commit 9e718d1

File tree

2 files changed

+15
-24
lines changed

2 files changed

+15
-24
lines changed

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

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,28 +17,16 @@
1717
public class _206 {
1818

1919
public static class Solution1 {
20-
/**
21-
* creating a newHead = null is a very common/smart way to handle such cases, the logic flows out very naturally:
22-
* create a new node called "next" to hold current head's next node
23-
* then we could redirect head's next pointer to point to newHead which is head's previous node
24-
* the above two steps finished the reversion, to continue this process until we reach the end of the original list,
25-
* we'll assign current "head" to new "newHead", and current "next" to be new "head" for the next iteration, here's the code
26-
*/
2720
public ListNode reverseList(ListNode head) {
28-
/**It works out the best to set up a debug point and visualize this process:
29-
* e.g. 1->2->3-null
30-
* at the end of the first iteration of the while loop, the status is like this:
31-
* newHead: 1->null
32-
* head: 2->3-null
33-
* then it continues the iteration.*/
34-
ListNode newHead = null;
35-
while (head != null) {
36-
ListNode next = head.next;
37-
head.next = newHead;
38-
newHead = head;
39-
head = next;
21+
ListNode prev = null;
22+
ListNode curr = head;
23+
while (curr != null) {
24+
ListNode next = curr.next;
25+
curr.next = prev;
26+
prev = curr;
27+
curr = next;
4028
}
41-
return newHead;
29+
return prev;
4230
}
4331
}
4432

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

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,13 @@ public static void setup() {
2121

2222
@Test
2323
public void test1() {
24-
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3});
25-
assertEquals(LinkedListUtils.contructLinkedList(new int[]{3, 2, 1}), solution1.reverseList(head));
24+
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4});
25+
assertEquals(LinkedListUtils.contructLinkedList(new int[]{4, 3, 2, 1}), solution1.reverseList(head));
26+
}
2627

27-
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3});
28-
assertEquals(LinkedListUtils.contructLinkedList(new int[]{3, 2, 1}), solution2.reverseList(head));
28+
@Test
29+
public void test2() {
30+
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4});
31+
assertEquals(LinkedListUtils.contructLinkedList(new int[]{4, 3, 2, 1}), solution2.reverseList(head));
2932
}
3033
}

0 commit comments

Comments
 (0)