栈-N1019-链表中的下一个更大节点

2019-04-11  本文已影响0人  三次元蚂蚁

题目

思路

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public int[] nextLargerNodes(ListNode head) {
        int[] temp = new int[10000];
        int index = 0;
        LinkedList<Node> stack = new LinkedList<>();
        Node top;
        ListNode cur = head;
        
        while (cur != null) {
            if (stack.isEmpty()) {
                stack.push(new Node(cur.val, index++));
                cur = cur.next;
            }
            
            if (cur == null) {
                break;
            }
            
            top = stack.peek();
            if (top.val < cur.val) {
                temp[top.index] = cur.val;
                stack.pop();
            } else {
                stack.push(new Node(cur.val, index++));
                cur = cur.next;
            }
        }
        
        while (!stack.isEmpty()) {
            temp[stack.pop().index] = 0;
        }
        
        int[] result = new int[index];
        for (int i = 0; i < index; ++i) {
            result[i] = temp[i];
        }
        
        return result;
    }
    
    private class Node {
        int val;
        int index;
        
        Node(int val, int index) {
            this.val = val;
            this.index = index;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读