Skip to content

added one pass solution and test case for 369 #155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/main/java/com/fishercoder/solutions/_369.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,33 @@ public ListNode plusOne(ListNode head) {
}
}

public static class Solution2 {

public ListNode plusOne(ListNode head) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;

ListNode notNineNode = dummyNode;

// find the right most node value != 9
while (head != null) {
if (head.val != 9) {
notNineNode = head;
}
head = head.next;
}

// increase the rightmost node value to 1
notNineNode.val ++;
notNineNode = notNineNode.next;

// set all the following node values with 9 to 0
while (notNineNode != null) {
notNineNode.val = 0;
notNineNode = notNineNode.next;
}
return dummyNode.val != 0 ? dummyNode : dummyNode.next;
}
}

}
29 changes: 29 additions & 0 deletions src/test/java/com/fishercoder/_369Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.fishercoder;

import com.fishercoder.common.classes.ListNode;
import com.fishercoder.common.utils.LinkedListUtils;
import com.fishercoder.solutions._203;
import com.fishercoder.solutions._369;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class _369Test {

private static _369.Solution2 solution2;
private static ListNode head;
private static ListNode expected;

@BeforeClass
public static void setup() {
solution2 = new _369.Solution2();
}

@Test
public void test1() {
head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 9});
expected = LinkedListUtils.contructLinkedList(new int[]{1, 3, 0});
assertEquals(expected, solution2.plusOne(head));
}
}