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

The following examples show how to use java.util.Deque#pollFirst() . 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: ZKUtil.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * BFS Traversal of all the children under path, with the entries in the list,
 * in the same order as that of the traversal. Lists all the children without
 * setting any watches.
 *
 * @param zkw
 *          - zk reference
 * @param znode
 *          - path of node
 * @return list of children znodes under the path
 * @throws KeeperException
 *           if unexpected ZooKeeper exception
 */
private static List<String> listChildrenBFSNoWatch(ZKWatcher zkw,
    final String znode) throws KeeperException {
  Deque<String> queue = new LinkedList<>();
  List<String> tree = new ArrayList<>();
  queue.add(znode);
  while (true) {
    String node = queue.pollFirst();
    if (node == null) {
      break;
    }
    List<String> children = listChildrenNoWatch(zkw, node);
    if (children == null) {
      continue;
    }
    for (final String child : children) {
      final String childPath = node + "/" + child;
      queue.add(childPath);
      tree.add(childPath);
    }
  }
  return tree;
}
 
Example 2
Source File: Solution11.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    if (len < 1) {
        return new int[0];
    }
    int[] res = new int[len - k + 1];
    Deque<Integer> deque = new ArrayDeque<>(k + 1);
    for (int i = 0; i < len; i++) {
        // 考虑删除队首元素
        if (i >= k && !deque.isEmpty() && deque.peekFirst() == i - k) {
            deque.pollFirst();
        }
        while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
            deque.pollLast();
        }
        deque.addLast(i);
        // 形成一个单调不减的队列,队首是滑动窗口的最大值
        // 记录结果集
        if (i >= k - 1) {
            res[i - k + 1] = nums[deque.peekFirst()];
        }
    }
    return res;
}
 
Example 3
Source File: Nodes.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Depth first search, in left-to-right order, of the node tree, using
 * an explicit stack, to find the next non-empty leaf node.
 */
@SuppressWarnings("unchecked")
protected final N findNextLeafNode(Deque<N> stack) {
    N n = null;
    while ((n = stack.pollFirst()) != null) {
        if (n.getChildCount() == 0) {
            if (n.count() > 0)
                return n;
        } else {
            for (int i = n.getChildCount() - 1; i >= 0; i--)
                stack.addFirst((N) n.getChild(i));
        }
    }

    return null;
}
 
Example 4
Source File: DistribStateManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * List a subtree including the root path, using breadth-first traversal.
 * @param root root path
 * @return list of full paths, with the root path being the first element
 */
default List<String> listTree(String root) throws NoSuchElementException, IOException, KeeperException, InterruptedException {
  Deque<String> queue = new LinkedList<String>();
  List<String> tree = new ArrayList<String>();
  if (!root.startsWith("/")) {
    root = "/" + root;
  }
  queue.add(root);
  tree.add(root);
  while (true) {
    String node = queue.pollFirst();
    if (node == null) {
      break;
    }
    List<String> children = listData(node);
    for (final String child : children) {
      final String childPath = node + (node.equals("/") ? "" : "/") + child;
      queue.add(childPath);
      tree.add(childPath);
    }
  }
  return tree;
}
 
Example 5
Source File: ZKTools.java    From uncode-schedule with Apache License 2.0 6 votes vote down vote up
/**
 * BFS Traversal of the system under pathRoot, with the entries in the list,
 * in the same order as that of the traversal.
 * <p>
 * <b>Important:</b> This is <i>not an atomic snapshot</i> of the tree ever,
 * but the state as it exists across multiple RPCs from zkClient to the
 * ensemble. For practical purposes, it is suggested to bring the clients to
 * the ensemble down (i.e. prevent writes to pathRoot) to 'simulate' a
 * snapshot behavior.
 * 
 * @param zk
 * @param pathRoot
 *          The znode path, for which the entire subtree needs to be listed.
 * @throws Exception
 */
public static List<String> listSubTreeBFS(ZooKeeper zk, final String pathRoot) throws Exception {
  Deque<String> queue = new LinkedList<String>();
  List<String> tree = new ArrayList<String>();
  queue.add(pathRoot);
  tree.add(pathRoot);

  while (true) {
    String node = queue.pollFirst();
    if (node == null) {
      break;
    }

    List<String> children = zk.getChildren(node, false);
    for (final String child : children) {
      final String childPath = node + "/" + child;
      queue.add(childPath);
      tree.add(childPath);
    }
  }
  return tree;
}
 
Example 6
Source File: Nodes.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Depth first search, in left-to-right order, of the node tree, using
 * an explicit stack, to find the next non-empty leaf node.
 */
@SuppressWarnings("unchecked")
protected final N findNextLeafNode(Deque<N> stack) {
    N n = null;
    while ((n = stack.pollFirst()) != null) {
        if (n.getChildCount() == 0) {
            if (n.count() > 0)
                return n;
        } else {
            for (int i = n.getChildCount() - 1; i >= 0; i--)
                stack.addFirst((N) n.getChild(i));
        }
    }

    return null;
}
 
Example 7
Source File: Nodes.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Depth first search, in left-to-right order, of the node tree, using
 * an explicit stack, to find the next non-empty leaf node.
 */
@SuppressWarnings("unchecked")
protected final N findNextLeafNode(Deque<N> stack) {
    N n = null;
    while ((n = stack.pollFirst()) != null) {
        if (n.getChildCount() == 0) {
            if (n.count() > 0)
                return n;
        } else {
            for (int i = n.getChildCount() - 1; i >= 0; i--)
                stack.addFirst((N) n.getChild(i));
        }
    }

    return null;
}
 
Example 8
Source File: TreeTraversals.java    From interview with Apache License 2.0 6 votes vote down vote up
public void inorderItr(Node root){
    Deque<Node> stack = new LinkedList<Node>();
    Node node = root;
    while(true){
        if(node != null){
            stack.addFirst(node);
            node = node.left;
        }
        else{
            if(stack.isEmpty()){
                break;
            }
            node = stack.pollFirst();
            System.out.println(node.data);
            node = node.right;
        }
    }
}
 
Example 9
Source File: DefaultZooKeeperClient.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> listRecursive(final String path) throws KeeperException {
  assertClusterIdFlagTrue();
  final Deque<String> queue = newLinkedList();
  final List<String> tree = newArrayList();

  queue.add(path);
  tree.add(path);

  while (!queue.isEmpty()) {
    final String node = queue.pollFirst();
    final List<String> children = getChildren(node);

    for (final String child : children) {
      final String childPath = node.replaceAll("/$", "") + "/" + child;
      queue.add(childPath);
      tree.add(childPath);
    }
  }

  return tree;
}
 
Example 10
Source File: OptionsParser.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Collects the arguments for a command line flag until it finds a flag that starts with the
 * terminatorPrefix.
 *
 * @param output where to put the collected flag arguments.
 * @param args
 * @param terminatorPrefix the terminator prefix to stop collecting of argument flags.
 */
private static void collectFlagArguments(
    Collection<String> output, Deque<String> args, String terminatorPrefix) {
  for (String arg = args.pollFirst(); arg != null; arg = args.pollFirst()) {
    if (arg.startsWith(terminatorPrefix)) {
      args.addFirst(arg);
      break;
    }
    output.add(arg);
  }
}
 
Example 11
Source File: AbstractParallelSourceBase.java    From alibaba-flink-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public InputSplit getNextInputSplit(String location, int taskIndex) {
	checkTaskIndex(taskIndex);
	Deque<InputSplit> unassignedSplitsForTask = unassignedSplitsByTask.get(taskIndex);
	InputSplit split = unassignedSplitsForTask.pollFirst();
	if (split != null) {
		assignedSplits.put(split.getSplitNumber(), taskIndex);
	}
	return split;
}
 
Example 12
Source File: DequeMultiMap.java    From whiskey with Apache License 2.0 5 votes vote down vote up
@Override
public V removeFirst(Object key) {

    int sentinel = mutations;
    Deque<V> values = map.get(key);
    if (values == null) return null;
    V value = values.pollFirst();
    size--;
    if (values.isEmpty()) map.remove(key);
    if (sentinel != mutations++) throw new ConcurrentModificationException();
    return value;
}
 
Example 13
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 14
Source File: WiggleHelper.java    From Wiggle with Apache License 2.0 5 votes vote down vote up
@Override
protected Frame extractFrameToFixPosition(long delayFrames, Deque<Frame> frameDeque) {
    if (frameDeque.size() > delayFrames) {
        return frameDeque.pollFirst();
    }
    return frameDeque.getFirst();
}
 
Example 15
Source File: FeedbackChannel.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  final Deque<T> buffer = queue.drainAll();
  try {
    T element;
    while ((element = buffer.pollFirst()) != null) {
      consumer.processFeedback(element);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 16
Source File: ConsString.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private synchronized void flatten(final boolean flattenNested) {
    // We use iterative traversal as recursion may exceed the stack size limit.
    final char[] chars = new char[length];
    int pos = length;
    // Strings are most often composed by appending to the end, which causes ConsStrings
    // to be very unbalanced, with mostly single string elements on the right and a long
    // linear list on the left. Traversing from right to left helps to keep the stack small
    // in this scenario.
    final Deque<CharSequence> stack = new ArrayDeque<>();
    stack.addFirst(left);
    CharSequence cs = right;

    do {
        if (cs instanceof ConsString) {
            final ConsString cons = (ConsString) cs;
            // Count the times a cons-string is traversed as part of other cons-strings being flattened.
            // If it crosses a threshold we flatten the nested cons-string internally.
            if (cons.state == STATE_FLATTENED || (flattenNested && ++cons.state >= STATE_THRESHOLD)) {
                cs = cons.flattened(false);
            } else {
                stack.addFirst(cons.left);
                cs = cons.right;
            }
        } else {
            final String str = (String) cs;
            pos -= str.length();
            str.getChars(0, str.length(), chars, pos);
            cs = stack.isEmpty() ? null : stack.pollFirst();
        }
    } while (cs != null);

    left = new String(chars);
    right = "";
    state = STATE_FLATTENED;
}
 
Example 17
Source File: SerializeDeserializeBinaryTree.java    From interview with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize tree using level order traversal.
 */
public String serializeLevelOrder(Node root) {
    if (root == null) {
        return "";
    }

    Deque<Node> queue = new LinkedList<>();
    queue.offerFirst(root);
    StringBuffer buff = new StringBuffer();
    while (!queue.isEmpty()) {
        root = queue.pollFirst();
        if (root == null) {
            buff.append("%,");
        } else {
            buff.append(root.data).append(",");
            queue.offer(root.left);
            queue.offer(root.right);
        }
    }
    for (int i = buff.length() - 1; i >= 0; i--) {
        if (buff.charAt(i) == '%' || buff.charAt(i) == ',') {
            buff.deleteCharAt(i);
        } else {
            break;
        }
    }
    return buff.toString();
}
 
Example 18
Source File: SeparateAndConquerStrategy.java    From RegexGenerator with GNU General Public License v3.0 5 votes vote down vote up
private Node joinSolutions(List<Node> bests) {
    Deque<Node> nodes = new LinkedList<>(bests);
    Deque<Node> tmp = new LinkedList<>();
    while (nodes.size() > 1) {

        while (nodes.size() > 0) {
            Node first = nodes.pollFirst();
            Node second = nodes.pollFirst();

            if (second != null) {
                Node or = new Or();
                or.getChildrens().add(first);
                or.getChildrens().add(second);
                first.setParent(or);
                second.setParent(or);
                tmp.addLast(or);
            } else {
                tmp.addLast(first);
            }
        }

        nodes = tmp;
        tmp = new LinkedList<>();

    }
    return nodes.getFirst();
}
 
Example 19
Source File: MCRFileSystemUtils.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
static MCRFile getMCRFile(MCRDirectory baseDir, MCRPath relativePath, boolean create, boolean createNew)
    throws IOException {
    MCRPath ifsPath = relativePath;
    if (relativePath.isAbsolute()) {
        if (baseDir.getOwnerID().equals(relativePath.getOwner())) {
            ifsPath = baseDir.toPath().relativize(relativePath);
        } else {
            throw new IOException(relativePath + " is absolute does not fit to " + baseDir.toPath());
        }
    }
    Deque<MCRFilesystemNode> created = new LinkedList<>();
    MCRFile file;
    try {
        file = (MCRFile) baseDir.getChildByPath(ifsPath.toString());
        if (file != null && createNew) {
            throw new FileAlreadyExistsException(baseDir.toPath().resolve(ifsPath).toString());
        }
        if (file == null & (create || createNew)) {
            Path normalized = ifsPath.normalize();
            MCRDirectory parent = baseDir;
            int nameCount = normalized.getNameCount();
            int directoryCount = nameCount - 1;
            int i = 0;
            while (i < directoryCount) {
                String curName = normalized.getName(i).toString();
                MCRDirectory curDir = (MCRDirectory) parent.getChild(curName);
                if (curDir == null) {
                    curDir = new MCRDirectory(curName, parent);
                    created.addFirst(curDir);
                }
                i++;
                parent = curDir;
            }
            String fileName = normalized.getFileName().toString();
            file = new MCRFile(fileName, parent);
            file.setContentFrom(new ByteArrayInputStream(new byte[0]), false);//false -> no event handler
            created.addFirst(file);
        }
    } catch (Exception e) {
        if (create || createNew) {
            LOGGER.error("Exception while getting MCRFile {}. Removing created filesystem nodes.", ifsPath);
            while (created.peekFirst() != null) {
                MCRFilesystemNode node = created.pollFirst();
                try {
                    node.delete();
                } catch (Exception de) {
                    LOGGER.fatal("Error while deleting file system node: {}", node.getName(), de);
                }
            }
        }
        throw e;
    }
    return file;
}
 
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;
}