From f6930f00314c0873f4cd212d9e2d7eb7b893bbfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=BD=A9=E8=BE=95=E9=BE=99=E5=84=BF?= Date: Mon, 10 Apr 2023 21:31:55 +0800 Subject: [PATCH] =?UTF-8?q?1019:=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E4=B8=8B=E4=B8=80=E4=B8=AA=E6=9B=B4=E5=A4=A7=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/NextGreaterNodeInLinkedList.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/main/java/leetcode/editor/cn/NextGreaterNodeInLinkedList.java b/src/main/java/leetcode/editor/cn/NextGreaterNodeInLinkedList.java index 57f6807..b6f5a0d 100644 --- a/src/main/java/leetcode/editor/cn/NextGreaterNodeInLinkedList.java +++ b/src/main/java/leetcode/editor/cn/NextGreaterNodeInLinkedList.java @@ -43,16 +43,14 @@ package leetcode.editor.cn; import com.code.leet.entiy.ListNode; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; +import java.util.*; //1019:链表中的下一个更大节点 public class NextGreaterNodeInLinkedList { public static void main(String[] args) { //测试代码 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) @@ -94,21 +92,20 @@ public class NextGreaterNodeInLinkedList { // } public int[] nextLargerNodes(ListNode head) { List result = new ArrayList<>(); - Queue queue = new LinkedList<>(); - Queue indexs = new LinkedList<>(); + Stack stack = new Stack<>(); + Stack indexs = new Stack<>(); int index = 0; while (head != null) { - while (!queue.isEmpty() && head.val > queue.peek()) { - result.set(indexs.poll(), head.val); - queue.poll(); + while (!stack.isEmpty() && head.val > stack.peek()) { + result.set(indexs.pop(), head.val); + stack.pop(); } - queue.add(head.val); + stack.add(head.val); indexs.add(index); result.add(0); index++; head = head.next; } - result.add(0); return result.stream().mapToInt(Integer::valueOf).toArray(); } }