Skip to content

Commit ef8ebbe

Browse files
authored
added one pass solution and test case for 369 (#155)
1 parent 6445bf9 commit ef8ebbe

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

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

+29
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,33 @@ public ListNode plusOne(ListNode head) {
5555
}
5656
}
5757

58+
public static class Solution2 {
59+
60+
public ListNode plusOne(ListNode head) {
61+
ListNode dummyNode = new ListNode(0);
62+
dummyNode.next = head;
63+
64+
ListNode notNineNode = dummyNode;
65+
66+
// find the right most node value != 9
67+
while (head != null) {
68+
if (head.val != 9) {
69+
notNineNode = head;
70+
}
71+
head = head.next;
72+
}
73+
74+
// increase the rightmost node value to 1
75+
notNineNode.val ++;
76+
notNineNode = notNineNode.next;
77+
78+
// set all the following node values with 9 to 0
79+
while (notNineNode != null) {
80+
notNineNode.val = 0;
81+
notNineNode = notNineNode.next;
82+
}
83+
return dummyNode.val != 0 ? dummyNode : dummyNode.next;
84+
}
85+
}
86+
5887
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.classes.ListNode;
4+
import com.fishercoder.common.utils.LinkedListUtils;
5+
import com.fishercoder.solutions._203;
6+
import com.fishercoder.solutions._369;
7+
import org.junit.BeforeClass;
8+
import org.junit.Test;
9+
10+
import static org.junit.Assert.assertEquals;
11+
12+
public class _369Test {
13+
14+
private static _369.Solution2 solution2;
15+
private static ListNode head;
16+
private static ListNode expected;
17+
18+
@BeforeClass
19+
public static void setup() {
20+
solution2 = new _369.Solution2();
21+
}
22+
23+
@Test
24+
public void test1() {
25+
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 9});
26+
expected = LinkedListUtils.contructLinkedList(new int[]{1, 3, 0});
27+
assertEquals(expected, solution2.plusOne(head));
28+
}
29+
}

0 commit comments

Comments
 (0)