Directory link:
Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog
GitHub synchronous brushing project:
https://github.com/September26/java-algorithms
Link to the original title: Likou
describe:
Given a n
linked list of lengthhead
For each node in the list, find the value of the next greater node . That is, for each node, find the value of the first node next to it that is strictly greater than its value.
Returns an array of integers answer
, where answer[i]
is the value of the next greater node of the -th i
node ( starting from 1 ). Set if the i
th node has no next greater node answer[i] = 0
.
Example 1:
Input: head = [2,1,5] Output: [5,5,0]
Example 2:
Input: head = [2,7,4,3,5] Output: [7,0,5,5,0]
hint:
- The number of nodes in the linked list is
n
1 <= n <= 104
1 <= Node.val <= 109
Problem-solving ideas:
* Problem-solving ideas: * Build a stack structure stack and traverse from back to front. * If the current value >= the value at the top of the stack, pop this value from the top of the stack. Continue to take the value at the top of the stack for comparison. * If the stack is empty, it means that there is no larger value behind, then set the value bit of the current position to 0. * If the current value < the value at the top of the stack, it means that the greater value at the current position is the value at the top of the stack.
code:
public class Solution1019 {
public int[] nextLargerNodes(ListNode head) {
Stack<Integer> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
int[] arr = new int[list.size()];
for (int i = list.size() - 1; i >= 0; i--) {
Integer value = list.get(i);
while (stack.size() > 0) {
Integer peek = stack.peek();
if (value >= peek) {
stack.pop();
} else {
break;
}
}
if (stack.size() == 0) {
arr[i] = 0;
} else {
arr[i] = stack.peek();
}
stack.add(value);
}
return arr;
}
}