LeetCode 1019. Next Greater Node In Linked List (链表中的下一个更大节点)

题目标签:Linked List, Stack

  题目给了我们一个 Linked List,让我们找出对于每一个数字,它的下一个更大的数字。

  首先把 Linked List 里的数字 存入 ArrayList, 方便后面的操作。

  然后遍历 ArrayList,首先每一个数字,都会存入stack;所以就可以利用stack回到之前的数字,存入它的 next Greater Node。

 

Java Solution:

Runtime:  39 ms, faster than 65 % 

Memory Usage: 40 MB, less than 95 %

完成日期:05/06/2019

关键点:利用stack

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] nextLargerNodes(ListNode head) {
        
        ArrayList<Integer> nums = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        int [] res;
        
        // save all numbers into ArrayList
        for(ListNode node = head; node != null; node = node.next)
            nums.add(node.val);
        
        res = new int[nums.size()];
        
        // use stack to find next greater element
        for(int i=0; i<nums.size(); i++)
        {
            // once find a greater num, it will check all previous numbers in stack
            while(!stack.isEmpty() && nums.get(stack.peek()) < nums.get(i))  
                res[stack.pop()] = nums.get(i);
            
            stack.push(i); // save index into stack
        }
        
        return res;
    }
}

参考资料:Le'e'tCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2019-07-07 06:47  Jimmy_Cheng  阅读(645)  评论(0编辑  收藏  举报