File tree 2 files changed +58
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -55,4 +55,33 @@ public ListNode plusOne(ListNode head) {
55
55
}
56
56
}
57
57
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
+
58
87
}
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments