Skip to content

Commit 885f069

Browse files
committed
add solution and testcase for 1019
1 parent 555f2ec commit 885f069

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
import com.fishercoder.common.classes.ListNode;
44

5+
import java.util.ArrayList;
6+
import java.util.List;
7+
import java.util.Stack;
8+
59
public class _1019 {
610
public static class Solution1 {
711
public int[] nextLargerNodes(ListNode head) {
@@ -37,4 +41,26 @@ private int findLength(ListNode head) {
3741
return count;
3842
}
3943
}
44+
public static class Solution2 {
45+
// Store the nodes of linked list into an array list
46+
// Create a stack that stores indexes, which would be needed to find the next greater element of
47+
// element at index i
48+
public int[] nextLargerNodes(ListNode head) {
49+
List<Integer> numList = new ArrayList<>();
50+
51+
for (ListNode temp = head; temp != null; temp = temp.next) {
52+
numList.add(temp.val);
53+
}
54+
Stack<Integer> stack = new Stack<>();
55+
int result[] = new int[numList.size()];
56+
for (int i = 0; i < numList.size(); i++) {
57+
58+
while (!stack.isEmpty() && numList.get(stack.peek()) < numList.get(i)) {
59+
result[stack.pop()] = numList.get(i);
60+
}
61+
stack.push(i);
62+
}
63+
return result;
64+
}
65+
}
4066
}

src/test/java/com/fishercoder/_1019Test.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,11 @@
1010

1111
public class _1019Test {
1212
private static _1019.Solution1 solution1;
13-
13+
private static _1019.Solution2 solution2;
1414
@BeforeClass
1515
public static void setup() {
1616
solution1 = new _1019.Solution1();
17+
solution2 = new _1019.Solution2();
1718
}
1819

1920
@Test
@@ -34,4 +35,9 @@ public void test3() {
3435
assertArrayEquals(new int[]{7, 9, 9, 9, 0, 5, 0, 0}, solution1.nextLargerNodes(head));
3536
}
3637

38+
@Test
39+
public void test4() {
40+
ListNode head = LinkedListUtils.contructLinkedList(new int[]{2, 7, 4, 3, 5});
41+
assertArrayEquals(new int[]{7, 0, 5, 5, 0}, solution2.nextLargerNodes(head));
42+
}
3743
}

0 commit comments

Comments
 (0)