1019:链表中的下一个更大节点

This commit is contained in:
轩辕龙儿 2023-04-10 21:31:55 +08:00
parent a8738e82f3
commit f6930f0031

View File

@ -43,16 +43,14 @@ package leetcode.editor.cn;
import com.code.leet.entiy.ListNode; import com.code.leet.entiy.ListNode;
import java.util.ArrayList; import java.util.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
//1019:链表中的下一个更大节点 //1019:链表中的下一个更大节点
public class NextGreaterNodeInLinkedList { public class NextGreaterNodeInLinkedList {
public static void main(String[] args) { public static void main(String[] args) {
//测试代码 //测试代码
Solution solution = new NextGreaterNodeInLinkedList().new Solution(); Solution solution = new NextGreaterNodeInLinkedList().new Solution();
solution.nextLargerNodes(new ListNode(Arrays.asList(2,7,4,3,5)));
} }
//力扣代码 //力扣代码
//leetcode submit region begin(Prohibit modification and deletion) //leetcode submit region begin(Prohibit modification and deletion)
@ -94,21 +92,20 @@ public class NextGreaterNodeInLinkedList {
// } // }
public int[] nextLargerNodes(ListNode head) { public int[] nextLargerNodes(ListNode head) {
List<Integer> result = new ArrayList<>(); List<Integer> result = new ArrayList<>();
Queue<Integer> queue = new LinkedList<>(); Stack<Integer> stack = new Stack<>();
Queue<Integer> indexs = new LinkedList<>(); Stack<Integer> indexs = new Stack<>();
int index = 0; int index = 0;
while (head != null) { while (head != null) {
while (!queue.isEmpty() && head.val > queue.peek()) { while (!stack.isEmpty() && head.val > stack.peek()) {
result.set(indexs.poll(), head.val); result.set(indexs.pop(), head.val);
queue.poll(); stack.pop();
} }
queue.add(head.val); stack.add(head.val);
indexs.add(index); indexs.add(index);
result.add(0); result.add(0);
index++; index++;
head = head.next; head = head.next;
} }
result.add(0);
return result.stream().mapToInt(Integer::valueOf).toArray(); return result.stream().mapToInt(Integer::valueOf).toArray();
} }
} }