Skip to content

Commit 7e0e8cd

Browse files
committed
Sixty-Eight Commit: Add Remove Nodes From Linked List problem to Monotonic Stack section
1 parent c142276 commit 7e0e8cd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Monotonic_Stack;
2+
3+
// Problem Statement: Remove Nodes From Linked List (easy)
4+
// LeetCode Question: 2487. Remove Nodes From Linked List
5+
6+
import java.util.Stack;
7+
8+
class ListNode {
9+
int val;
10+
ListNode next;
11+
ListNode(int val){
12+
this.val = val;
13+
}
14+
}
15+
public class Problem_3_Nodes_From_Linked_List {
16+
17+
public ListNode removeNodes(ListNode head){
18+
Stack<ListNode> stack = new Stack<>();
19+
ListNode cur = head;
20+
while (cur != null) {
21+
while (!stack.isEmpty() && stack.peek().val < cur.val){
22+
stack.pop();
23+
}
24+
if (!stack.isEmpty()) {
25+
stack.peek().next = cur;
26+
}
27+
stack.push(cur);
28+
cur = cur.next;
29+
}
30+
return stack.isEmpty() ? null : stack.get(0);
31+
}
32+
}

0 commit comments

Comments
 (0)