Java Code Examples for java.util.Deque#pollLast()

The following examples show how to use java.util.Deque#pollLast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IgniteQueryTreeRenderer.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Flattens a subtree of kind "op[A, op[op[B, C], ...]]"
 * (or similar) into "op[A, B, C, ...]". Useful for nodes
 * representing multipart dis/conjunctions and arithmetic
 * expressions to skip unnecessary parentheses
 */
private static void flattenSubtree(Tree node) {
	if ( firstChildOfType( node, node.getType() ) == null ) {
		return;
	}
	Deque<Tree> s = new ArrayDeque<>();
	Deque<Tree> m = new ArrayDeque<>();
	s.add( node );
	Tree n;
	while ( ( n = s.pollLast() ) != null ) {
		if ( n.getType() == node.getType() ) {
			for ( int i = 0; i < n.getChildCount(); ++i ) {
				s.add( n.getChild( i ) );
			}
		}
		else {
			m.add( n );
		}
	}
	for ( int i = 0; i < node.getChildCount(); ++i ) {
		node.setChild( i, m.pollLast() );
	}
	while ( ( n = m.pollLast() ) != null ) {
		node.addChild( n );
	}
}
 
Example 2
Source File: AbstractHoodieLogRecordScanner.java    From hudi with Apache License 2.0 6 votes vote down vote up
/**
 * Process the set of log blocks belonging to the last instant which is read fully.
 */
private void processQueuedBlocksForInstant(Deque<HoodieLogBlock> lastBlocks, int numLogFilesSeen) throws Exception {
  while (!lastBlocks.isEmpty()) {
    LOG.info("Number of remaining logblocks to merge " + lastBlocks.size());
    // poll the element at the bottom of the stack since that's the order it was inserted
    HoodieLogBlock lastBlock = lastBlocks.pollLast();
    switch (lastBlock.getBlockType()) {
      case AVRO_DATA_BLOCK:
        processDataBlock((HoodieAvroDataBlock) lastBlock);
        break;
      case DELETE_BLOCK:
        Arrays.stream(((HoodieDeleteBlock) lastBlock).getKeysToDelete()).forEach(this::processNextDeletedKey);
        break;
      case CORRUPT_BLOCK:
        LOG.warn("Found a corrupt block which was not rolled back");
        break;
      default:
        break;
    }
  }
  // At this step the lastBlocks are consumed. We track approximate progress by number of log-files seen
  progress = numLogFilesSeen - 1 / logFilePaths.size();
}
 
Example 3
Source File: TreeModelDataConverter.java    From Alink with Apache License 2.0 5 votes vote down vote up
public static List <String> serializeTree(Node node) {
	List <String> serialized = new ArrayList <>();

	int id = 0;

	Deque <NodeSerializable> nodeQ = new ArrayDeque <>();

	nodeQ.addFirst(new NodeSerializable()
		.setNode(node)
		.setId(id++)
	);

	while (!nodeQ.isEmpty()) {
		NodeSerializable nodeSerializable = nodeQ.pollLast();

		if (!(nodeSerializable.node.isLeaf())) {
			int len = nodeSerializable.node.getNextNodes().length;

			int[] nextIds = new int[len];

			for (int j = 0; j < nodeSerializable.node.getNextNodes().length; ++j) {
				nextIds[j] = id;
				nodeQ.addFirst(
					new NodeSerializable()
						.setNode(nodeSerializable.node.getNextNodes()[j])
						.setId(id++)
				);
			}

			nodeSerializable.setNextIds(nextIds);
		}

		serialized.add(JsonConverter.toJson(nodeSerializable));
	}

	return serialized;
}
 
Example 4
Source File: MemoryManager.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static ByteBuffer alloc0(int size) {
    ByteBuffer result = null;
    ThreadData local = getThreadData();
    int index = 32 - Integer.numberOfLeadingZeros(size-1);
    
    // allocate aligned memory if it is less than MAX_CACHE_SIZE
    
    if (size <= MAX_CACHE_BLOCK_SIZE) {
        Deque<ByteBuffer> q = local.buffers[index];
        result = q.pollLast();
        if (result != null) {
            local.pooled -= result.capacity();
        }
    }
    
    // allocate whatever it is if it is too big
    
    if (result == null) {
        int roundedSize = 1 << index;
        _log.trace("ByteBuffer.allocateDirect {}", roundedSize);
        result = ByteBuffer.allocateDirect(roundedSize);
        result.order(ByteOrder.nativeOrder());
    }
    
    // track the allocation
    
    if (_isDebugEnabled) {
        local.allocated += result.capacity();
    }
    if (_isTraceEnabled) {
        if (local.traces == null) {
            local.traces = new HashMap<>();
        }
        local.traces.put(UberUtil.getAddress(result), new Exception());
    }
    
    // done
    
    return result;
}
 
Example 5
Source File: ConditionBuilder.java    From Despector with MIT License 5 votes vote down vote up
private static void dfs(ConditionGraphNode next, Deque<Condition> stack) {

        // performs a depth-first-search to populate each node in the graph's
        // partial conditions

        if (!stack.isEmpty()) {
            // Add the condition up to this point to the partial conditions of
            // this node. This represents a path from the root to this node and
            // the condition of that path is the and of all simple conditions of
            // the nodes along the path
            if (stack.size() == 1) {
                next.addPartialCondition(stack.peek());
            } else {
                Condition partial = new AndCondition(stack);
                next.addPartialCondition(partial);
            }
        }
        if (next.getSimpleCondition() == null) {
            return;
        }
        // Push the simple condition of this node to the stack and recurse into
        // the target branch
        stack.addLast(next.getSimpleCondition());
        dfs(next.getTarget(), stack);
        stack.pollLast();
        // Same thing for the else_target except we push the inverse of this
        // node's condition
        stack.addLast(inverse(next.getSimpleCondition()));
        dfs(next.getElseTarget(), stack);
        stack.pollLast();
    }
 
Example 6
Source File: RuntimeCCTNodeProcessor.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private static void processStack(int maxMethodId, Deque<Item<RuntimeCCTNode>> stack, Plugin ... plugins) {
    while (!stack.isEmpty()) {
        Item<RuntimeCCTNode> item = stack.pollLast();
        if (item != null) {
            item.process(maxMethodId);
        }
    }
}
 
Example 7
Source File: RuntimeCCTNodeProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void processStack(int maxMethodId, Deque<Item<RuntimeCCTNode>> stack, Plugin ... plugins) {
    while (!stack.isEmpty()) {
        Item<RuntimeCCTNode> item = stack.pollLast();
        if (item != null) {
            item.process(maxMethodId);
        }
    }
}
 
Example 8
Source File: NavigatorService.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
/**
 * 格式化RouteModel的路书展现形式,将间隔只有100米的行驶缓慢或拥堵的路段合并为拥堵
 *
 * @param nodes  RouteModel路书中的路段集合
 * @param tIndex 需要遍历的路段的最大索引值,tIndex<nodes.size();
 * @return 双向队列,size()=奇数,索引奇数的int代表拥堵路段的长度,索引偶数的int代表顺畅路段的长度
 */
private Deque<FormatTrafficNode> formatConjestionDistance(List<RouteModel.RouteNode> nodes, int tIndex) {
    Deque<FormatTrafficNode> dists = new ArrayDeque<FormatTrafficNode>();
    int t;
    RouteModel.RouteNode node = null;
    for (int i = 0; i <= tIndex; ++i) {
        if (dists.size() == 0) {
            if ((node = nodes.get(i)).getRoadCondition() > RouteModel.ROAD_CONDITION_TYPE_Straightway) {
                dists.offer(new FormatTrafficNode(node.getDistance(), node.getDistanceFromStart(), node.getName(), true));
            }
        } else {
            t = dists.size();
            node = nodes.get(i);
            if ((t & 1) == 1) {//奇数,拥堵长度
                if (node.getRoadCondition() > RouteModel.ROAD_CONDITION_TYPE_Straightway) {
                    dists.getLast().append(node.getDistance(), node.getName());
                } else {
                    dists.offer(new FormatTrafficNode(node.getDistance(), node.getDistanceFromStart(), node.getName()));
                }
            } else {//偶数,顺畅长度
                if (node.getRoadCondition() > RouteModel.ROAD_CONDITION_TYPE_Straightway) {
                    if (dists.getLast().getDistance() <= 100) {
                        dists.pollLast();
                        dists.getLast().append(node.getDistance(), node.getName());
                    } else {
                        dists.offer(new FormatTrafficNode(node.getDistance(), node.getDistanceFromStart(), node.getName(), true));
                    }
                } else {
                    dists.getLast().append(node.getDistance(), node.getName());
                }
            }
        }
    }
    if ((dists.size() & 1) == 0) {
        dists.pollLast();
    }
    return dists;
}
 
Example 9
Source File: NavigatorService.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
private Deque<Integer> formatConjestionDistance(List<RoadConditionItem> conditionItems, int eIndex, double totalDistance) {
    Deque<Integer> dists = new ArrayDeque<Integer>();
    RoadConditionItem item;
    int t;
    double maxIndex = conditionItems.get(conditionItems.size() - 1).curItemEndIndex;
    for (RoadConditionItem conditionItem : conditionItems) {
        conditionItem.curItemEndIndex = (int) (conditionItem.curItemEndIndex / maxIndex * totalDistance);
    }
    for (int i = 0; i < eIndex; i++) {
        item = conditionItems.get(i);
        if (dists.size() == 0) {
            if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                dists.offer(i == 0 ? item.curItemEndIndex : item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex);
            }
        } else {
            t = dists.size();
            if ((t & 1) == 1) {//奇数,拥堵长度
                if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                    dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                } else {
                    dists.offer((item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                }
            } else {//偶数,顺畅长度
                if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                    if (dists.getLast() <= 100) {
                        dists.pollLast();
                        dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                    } else {
                        dists.offer((item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                    }
                } else {
                    dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                }
            }
        }
    }
    return dists;
}
 
Example 10
Source File: InventoryGui.java    From InventoryGui with MIT License 5 votes vote down vote up
/**
 * Go back one entry in the history
 * @param player    The player to show the previous gui to
 * @return          <tt>true</tt> if there was a gui to show; <tt>false</tt> if not
 */
public static boolean goBack(HumanEntity player) {
    Deque<InventoryGui> history = getHistory(player);
    history.pollLast();
    if (history.isEmpty()) {
        return false;
    }
    InventoryGui previous = history.peekLast();
    if (previous != null) {
        previous.show(player, false);
    }
    return true;
}
 
Example 11
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public String removeKdigits(String num, int k) {
    int len = num.length();
    if (len == k) {
        return "0";
    }

    int remaining = len - k;
    char[] charArray = num.toCharArray();
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : charArray) {
        while (k > 0 && !stack.isEmpty() && stack.peekLast() > c) {
            stack.removeLast();
            k--;
        }
        stack.addLast(c);
    }

    // System.out.println(stack);
    // 只取前面剩下的部分,针对 String num = "112"; int k = 1; 这种用例
    while (stack.size() > remaining) {
        stack.pollLast();
    }

    while (!stack.isEmpty() && stack.peekFirst() == '0') {
        stack.removeFirst();
    }

    if (stack.isEmpty()) {
        return "0";
    }
    return toString(stack);
}
 
Example 12
Source File: DFSCore.java    From psjava with MIT License 5 votes vote down vote up
public static <V, E> void traverse(
        V start,
        AdjacencyList<V, E> adj,
        Function<E, V> destination,
        Function<V, DFSStatus> getStatus,
        BiConsumer<V, DFSStatus> setStatus,
        DFSVisitor<V, E> visitor
) {

    Deque<StackItem<V, E>> stack = new ArrayDeque<>();
    setStatus.accept(start, DFSStatus.DISCOVERED);
    SimpleStopper stopper = new SimpleStopper();
    visitor.onDiscovered(start, 0, stopper);
    Iterator<E> iterator = adj.get(start).iterator();
    stack.push(new StackItem<>(null, start, 0, iterator));

    while (!stack.isEmpty() && !stopper.isStopped()) {
        StackItem<V, E> item = stack.peekLast();

        if (item.remainEdges.hasNext()) {
            E edge = item.remainEdges.next();
            V dest = destination.apply(edge);
            DFSStatus destStatus = getStatus.apply(dest);
            if (destStatus == null) {
                visitor.onWalkDown(edge);
                setStatus.accept(item.vertex, DFSStatus.DISCOVERED);
                visitor.onDiscovered(dest, item.depth + 1, stopper);
                stack.addLast(new StackItem<>(edge, dest, item.depth + 1, adj.get(dest).iterator()));
            } else if (destStatus == DFSStatus.DISCOVERED) {
                visitor.onBackEdgeFound(edge);
            }
        } else {
            stack.pollLast();
            setStatus.accept(item.vertex, DFSStatus.EXPLORED);
            visitor.onFinish(item.vertex);
            if (item.previousEdgeOrNull != null)
                visitor.onWalkUp(item.previousEdgeOrNull);
        }
    }
}
 
Example 13
Source File: Solution8.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public int largestRectangleArea(int[] heights) {
    int len = heights.length;
    if (len == 0) {
        return 0;
    }

    if (len == 1) {
        return heights[0];
    }

    int res = 0;

    int[] newHeights = new int[len + 2];
    newHeights[0] = 0;
    System.arraycopy(heights, 0, newHeights, 1, len);
    newHeights[len + 1] = 0;
    len += 2;
    heights = newHeights;

    Deque<Integer> stack = new ArrayDeque<>(len);
    for (int i = 0; i < len; i++) {

        while (!stack.isEmpty() && heights[i] < heights[stack.peekLast()]) {
            int curHeight = heights[stack.pollLast()];

            while (!stack.isEmpty() && heights[stack.peekLast()] == curHeight) {
                stack.pollLast();
            }

            int curWidth = i - stack.peekLast() - 1;

            res = Math.max(res, curHeight * curWidth);
        }
        stack.add(i);
    }
    return res;
}
 
Example 14
Source File: MarshallerPool.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Removes expired (un)marshallers from the given queue.
 *
 * @param  <T>    either {@code Marshaller} or {@code Unmarshaller} type.
 * @param  queue  the queue from which to remove expired (un)marshallers.
 * @param  now    current value of {@link System#nanoTime()}.
 * @return {@code true} if the queue became empty as a result of this method call.
 */
private static <T> boolean removeExpired(final Deque<T> queue, final long now) {
    T next;
    while ((next = queue.peekLast()) != null) {
        /*
         * The above line fetched the oldest (un)marshaller without removing it.
         * If the timeout is not yet elapsed, do not remove that (un)marshaller.
         * Since marshallers are enqueued in chronological order, the next ones
         * should be yet more recent, so it is not worth to continue the search.
         */
        if (now - ((Pooled) next).resetTime < TIMEOUT) {
            return false;
        }
        /*
         * Now remove the (un)marshaller and check again the timeout. This second
         * check is because the oldest (un)marshaller may have changed concurrently
         * (depending on the queue implementation, which depends on the target JDK).
         * If such case, restore the (un)marshaller on the queue.
         */
        next = queue.pollLast();
        if (now - ((Pooled) next).resetTime < TIMEOUT) {
            queue.addLast(next);
            return false;
        }
    }
    return true;
}
 
Example 15
Source File: NBTReflectionUtil.java    From Crazy-Crates with MIT License 5 votes vote down vote up
protected static Object gettoCompount(Object nbttag, NBTCompound comp) {
    Deque<String> structure = new ArrayDeque<>();
    while (comp.getParent() != null) {
        structure.add(comp.getName());
        comp = comp.getParent();
    }
    while (!structure.isEmpty()) {
        String target = structure.pollLast();
        nbttag = getSubNBTTagCompound(nbttag, target);
        if (nbttag == null) {
            throw new NbtApiException("Unable to find tag '" + target + "' in " + nbttag);
        }
    }
    return nbttag;
}
 
Example 16
Source File: Test65.java    From algorithm-primer with MIT License 5 votes vote down vote up
public ArrayList<Integer> maxInWindows(int[] num, int size) {
    ArrayList<Integer> result = new ArrayList<>();
    if (num == null || num.length == 0 || size < 1) return result;

    Deque<Integer> deque = new LinkedList<>();
    for (int i = 0; i < num.length; i ++){
        // 保证添加新的元素之前,窗口中首尾元素下标之差最大是size
        if (i > 0 && !deque.isEmpty()){
            int firstIdx = deque.peekFirst();
            int diff = i - firstIdx;
            if (diff == size)
                deque.pollFirst();
        }
        /*
        if (!deque.isEmpty() && num[i] > deque.peekFirst()){
            deque.clear();
        }else{
            while(!deque.isEmpty() && num[i] >= deque.peekLast())
                deque.pollLast();
        }
        */

        // 同一个窗口中的元素如果小于新元素,则被删除
        // 由于前面的元素总是大于后面的元素,所以从后面开始删除
        while(!deque.isEmpty() && num[i] >= num[deque.peekLast()])
            deque.pollLast();

        // 新元素总是会被添加到双端队列的末尾
        deque.offerLast(i);

        // 双端队列的队头存放的是一个窗口的最大值
        if (i >= size-1)
            result.add(num[deque.peekFirst()]);
    }
    return result;
}
 
Example 17
Source File: _059_Max_Value_In_Slide_Window.java    From algorithm-primer with MIT License 5 votes vote down vote up
public ArrayList<Integer> maxInWindows(int[] num, int size) {
    ArrayList<Integer> result = new ArrayList<>();
    if (num == null || num.length == 0 || size < 1) return result;

    Deque<Integer> deque = new LinkedList<>();
    for (int i = 0; i < num.length; i ++){

        // 保证添加新的元素之前,窗口中首尾元素下标之差最大是size
        if (i > 0 && !deque.isEmpty()){
            int firstIdx = deque.peekFirst();
            int diff = i - firstIdx;
            if (diff == size) {
                deque.pollFirst();
            }
        }

        // 同一个窗口中的元素如果小于新元素,则被删除
        // 由于前面的元素总是大于后面的元素,所以从后面开始删除
        while(!deque.isEmpty() && num[i] >= num[deque.peekLast()]) {
            deque.pollLast();
        }

        // 新元素总是会被添加到双端队列的末尾
        deque.offerLast(i);

        // 双端队列的队头存放的是一个窗口的最大值
        if (i >= size-1) {
            result.add(num[deque.peekFirst()]);
        }
    }
    return result;
}
 
Example 18
Source File: SearchBuilder.java    From gadtry with Apache License 2.0 5 votes vote down vote up
/**
 * 深度优先 Depth first
 */
private static <E, R> void searchByDepthFirst(
        Deque<Route<E, R>> routes,
        SearchContext<E, R> context,
        Route<E, R> beginNode)
{
    final Deque<Route<E, R>> nextNodes = new LinkedList<>();  //Stack
    nextNodes.add(beginNode);

    Route<E, R> route;
    while ((route = nextNodes.pollLast()) != null) {
        for (Edge<E, R> edge : route.getLastNode().nextNodes()) {   //use stream.parallel();
            Route<E, R> newRoute = route.copy().add(edge).create();
            context.setLastRoute(newRoute);

            if (context.getNextRule().apply(newRoute)) {
                routes.add(newRoute);
                nextNodes.add(newRoute);
            }

            if (!context.getGlobalRule().apply(context)) {
                nextNodes.clear();
                return;
            }
        }
    }
}
 
Example 19
Source File: MaximumOfSubarrayOfSizeK.java    From interview with Apache License 2.0 5 votes vote down vote up
public int[] maxSubArray(int input[], int k) {
    Deque<Integer> queue = new LinkedList<Integer>();
    int max[] = new int[input.length - k + 1];
    int maxVal = Integer.MIN_VALUE;
    //first find max of first k values and make it 0th element of max array
    for (int i = 0; i < k; i++) {
        if(maxVal < input[i]){
            maxVal = input[i];
        }
        if (queue.isEmpty()) {
            queue.offerLast(i);
        } else {
            while (!queue.isEmpty() && input[queue.peekLast()] <= input[i]) {
                queue.pollLast();
            }
            queue.offerLast(i);
        }
        
    }
    max[0] = maxVal;
    int index=1;
    //continue from k till end of the input array
    for (int i = k; i < input.length; i++) {
        //if index of peek is k distance from i then its no value to us.
        //throw it away
        if (i - k + 1 > queue.peekFirst()) {
            queue.pollFirst();
        }
        while (!queue.isEmpty() && input[queue.peekLast()] <= input[i]) {
            queue.pollLast();
        }
        queue.offerLast(i);
        //Only reason first element survived was because it was biggest element.
        //make it the max value for this k
        max[index] = input[queue.peekFirst()];
        index++;
    }
    return max;
}
 
Example 20
Source File: TextBlockRenderer.java    From Spark-Reader with GNU General Public License v3.0 4 votes vote down vote up
private int renderLine(TextBlock text, Graphics g, int x, int y)
{
    if(text.getText() == null)return y;//don't render null text
    int startY = y;
    FontMetrics font = g.getFontMetrics();
    TextStream stream = new TextStream(text.getText());
    StringBuilder line = new StringBuilder();
    Deque<String> lines = new LinkedList<>();
    while(!stream.isDone())
    {
        String nextBit = stream.nextWord();
        if(font.stringWidth(line + nextBit) > width)//too much for this line, wrap over
        {
            lines.add(line.toString());//add line for rendering
            line = new StringBuilder(nextBit.trim());//put word on new line
        }
        else
        {
            line.append(nextBit);
        }
    }
    if(!line.toString().equals(""))lines.add(line.toString());//add last line
    //draw lines
    while(!lines.isEmpty())
    {
        if(displayUpwards) line = new StringBuilder(lines.pollLast());
        else line = new StringBuilder(lines.pollFirst());
        //draw line
        defLines++;
        if(startLine <= defLines)
        {
            if(displayUpwards)y -= font.getHeight();
            if(!displayUpwards) y += font.getHeight();

            //print background
            g.setColor(text.getBackCol());
            g.fillRect(x, y - font.getAscent(), width, font.getHeight());

            //print text
            g.setColor(text.getTextCol());
            g.drawString(line.toString(), x, y);

        }
    }
    //'gap' between def lines
    g.setColor(new Color(0, 0, 0, 1));
    g.clearRect(x, y - font.getAscent() + (displayUpwards?0:font.getHeight() - 1), width,1);//clear this last line
    g.fillRect (x, y - font.getAscent() + (displayUpwards?0:font.getHeight() - 1), width,1);//add a dim line here so scrolling still works

    //capture if in this
    if(capturePoint <= -1 || (displayUpwards?
            (capturePoint <= startY - font.getHeight() + font.getDescent() && capturePoint > y - font.getHeight() + font.getDescent()):
            (capturePoint > startY + font.getDescent() && capturePoint <= y + font.getDescent())))
    {
        //TODO allow export with HTML color info perhaps?
        if(capture.equals(""))
        {
            capture = text.getText();
        }
        else
        {
            capture += "\n" + text;
        }
    }

    return y;
}