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

The following examples show how to use java.util.LinkedList#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: DateRuleConverter.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String convert(QueryBuilderRuleNode node, DataType dataType, String operator) throws QueryBuilderToEqlConversionException {
    Object[] values = QueryBuilderUtil.getRuleNodeValueAsArray(node);
    LinkedList<Object> valuesList = new LinkedList<>(Arrays.asList(values));
    String value = (String) valuesList.pop();

    if (!TODAY.equalsIgnoreCase(value)) {
        value = SINGLE_QUOTE + value + SINGLE_QUOTE;
    } else {
        value = TODAY;
        if (valuesList.size() > MIN_EXPECTED_SIZE) {
            String rawValue = (String) valuesList.pop();
            if (StringUtils.isNotBlank(rawValue)) {
                int offset = parseOffset(node, rawValue);
                String sign = valuesList.pop().equals("sub") ? MINUS : PLUS;
                value += sign;
                value += Math.abs(offset);
            }

        }
    }

    return GRAVE_ACCENT + node.getId() + GRAVE_ACCENT + WHITESPACE + operator +
            WHITESPACE + value + DATE_FORMAT + SINGLE_QUOTE + valuesList.pollLast() + SINGLE_QUOTE;
}
 
Example 2
Source File: CacheCore.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
private void addException(TopologyMaster.TmasterExceptionLog exceptionLog) {
  String componentName = exceptionLog.getComponentName();
  String instanceId = exceptionLog.getInstanceId();
  assureComponentInstance(componentName, instanceId);
  // get exception idx
  int idx = idxComponentInstance.get(componentName).get(instanceId);
  // fetch the bucket
  if (!cacheException.containsKey(idx)) {
    cacheException.put(idx, new LinkedList<ExceptionDatapoint>());
  }
  LinkedList<ExceptionDatapoint> bucket = cacheException.get(idx);
  // store the exception
  ExceptionDatapoint e = new ExceptionDatapoint(exceptionLog.getHostname(),
      exceptionLog.getStacktrace(), exceptionLog.getLasttime(), exceptionLog.getFirsttime(),
      exceptionLog.getCount(), exceptionLog.getLogging());
  bucket.offerFirst(e);
  // purge
  while (bucket.size() > maxExceptionCount) {
    LOG.warning("too many exception, reach exception cache size cap, drop it: " + exceptionLog);
    bucket.pollLast();
  }
}
 
Example 3
Source File: TreeUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static Couple<ASTNode> findTopmostSiblingParents(ASTNode one, ASTNode two) {
  if (one == two) return Couple.of(null, null);

  LinkedList<ASTNode> oneParents = new LinkedList<>();
  while (one != null) {
    oneParents.add(one);
    one = one.getTreeParent();
  }
  LinkedList<ASTNode> twoParents = new LinkedList<>();
  while (two != null) {
    twoParents.add(two);
    two = two.getTreeParent();
  }

  do {
    one = oneParents.pollLast();
    two = twoParents.pollLast();
  }
  while (one == two && one != null);

  return Couple.of(one, two);
}
 
Example 4
Source File: SlidingWindowMaxArray.java    From Project with Apache License 2.0 5 votes vote down vote up
public static int[] getMaxWindow(int[] arr, int w) {
    if (arr == null || w < 1 || arr.length < w) {
        return null;
    }
    // LinkedList 就是一个标准的双向链表
    LinkedList<Integer> maxList = new LinkedList<Integer>();
    // 生成的结果数组
    int[] res = new int[arr.length - w + 1];
    int index = 0;
    for (int i = 0; i < arr.length; i++) {
        // 更新双端队列,如果双端队列不为空,并且尾结点(存的是下标)对应数组中的值是否小于等于当前值
        while (!maxList.isEmpty() && arr[maxList.peekLast()] <= arr[i]) {
            maxList.pollLast();
        }
        // 上面一直弹出,直到不符合然后加上当前值。
        maxList.addLast(i);
        // 上面加法是通用的,但是减法是针对该题定制的
        // 当过期的时候(当窗口形成之后再扩充才算过期)即窗口长度 > w,窗口形成过程中不会过期, i - w表示过期的下标
        if (maxList.peekFirst() == i - w) {
            maxList.pollFirst();
        }
        // 判断下标过期
        if (i >= w - 1) {
            // 当窗口已经形成了,记录每一步的res
            res[index++] = arr[maxList.peekFirst()];
        }
    }
    return res;
}
 
Example 5
Source File: Solution.java    From codekata with MIT License 5 votes vote down vote up
public List<String> letterCombinations(String digits) {
    LinkedList<String> result = new LinkedList<>();
    if (digits.length() == 0) return result;

    result.add("");
    for (int i = 0; i < digits.length(); i++) {
        int count = result.size();
        for (int j = 0; j < count; j++) {
            String last = result.pollLast();
            for (String value : map.get(digits.charAt(i))) result.push(last + value);
        }
    }

    return result;
}
 
Example 6
Source File: Script.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private static void executeCheckSig(Tx txContainingThis, int index, Script script, LinkedList<byte[]> stack,
                                    int lastCodeSepLocation, int opcode) throws ScriptException {
    if (stack.size() < 2)
        throw new ScriptException("Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2");
    byte[] pubKey = stack.pollLast();
    byte[] sigBytes = stack.pollLast();

    byte[] prog = script.getProgram();
    byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length);

    UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sigBytes.length + 1);
    try {
        writeBytes(outStream, sigBytes);
    } catch (IOException e) {
        throw new RuntimeException(e); // Cannot happen
    }
    connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray());

    // TODO: Use int for indexes everywhere, we can't have that many inputs/outputs
    boolean sigValid = false;
    try {
        TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, false);
        byte[] hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags);
        sigValid = ECKey.verify(hash, sig, pubKey);
    } catch (Exception e1) {
        // There is (at least) one exception that could be hit here (EOFException, if the sig is too short)
        // Because I can't verify there aren't more, we use a very generic Exception catch
        log.warn(e1.toString());
    }

    if (opcode == OP_CHECKSIG)
        stack.add(sigValid ? new byte[]{1} : new byte[]{0});
    else if (opcode == OP_CHECKSIGVERIFY)
        if (!sigValid)
            throw new ScriptException("Script failed OP_CHECKSIGVERIFY");
}
 
Example 7
Source File: CommandInjection.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String transferThroughList(String in, int index) {
    LinkedList<String> list = new LinkedList<String>();
    list.add(System.getenv("")); // taints the list
    list.clear(); // makes the list safe again
    list.add(1, "xx");
    list.addFirst(in); // can taint the list
    list.addLast("yy");
    list.push(in);
    return list.element() + list.get(index) + list.getFirst() + list.getLast()
            + list.peek() + list.peekFirst() + list.peekLast() + list.poll()
            + list.pollFirst() + list.pollLast() + list.pop() + list.remove()
            + list.remove(index) + list.removeFirst() + list.removeLast()
            + list.set(index, "safe") + list.toString();
}
 
Example 8
Source File: DataFilePool.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void closeUnused ()
{
    final int instances = this.usedPool.size () + this.freePool.size ();

    int num = instances - this.instanceCountTarget;

    if ( num <= 0 )
    {
        return;
    }

    logger.debug ( "Trying to reduce by {}", num );

    final LinkedList<AccessorWrapper> entries = new LinkedList<AccessorWrapper> ( this.freePool.values () );

    // sort by access date
    Collections.sort ( entries, new Comparator<AccessorWrapper> () {
        @Override
        public int compare ( final AccessorWrapper o1, final AccessorWrapper o2 )
        {
            return o1.getLastAccess ().compareTo ( o2.getLastAccess () );
        }

    } );

    while ( !this.freePool.isEmpty () && !entries.isEmpty () && num > 0 )
    {
        final AccessorWrapper entry = entries.pollLast ();

        logger.debug ( "Removing {} from pool", entry.getFile () );
        this.freePool.remove ( entry.getFile () );
        entry.getTarget ().dispose ();

        num--;
    }
}
 
Example 9
Source File: IOUtil.java    From timecat with Apache License 2.0 5 votes vote down vote up
private static void deleteContent(File file) {
    LinkedList<File> themeLinkedList = new LinkedList<File>();
    if (file.isDirectory()) {
        themeLinkedList.addAll(Arrays.asList(file.listFiles()));
        while (!themeLinkedList.isEmpty()) {
            File subFile = themeLinkedList.pollLast();
            deleteContent(subFile);
        }
    }
    file.delete();
}
 
Example 10
Source File: Solution3.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public boolean isSymmetric(TreeNode root) {
    if (root == null) {
        return true;
    }
    LinkedList<TreeNode> queue = new LinkedList<>();
    queue.addFirst(root.left);
    queue.addLast(root.right);
    while (!queue.isEmpty()) {
        // 出队的时候,看看是否有左右孩子,分别入队
        TreeNode leftNode = queue.pollFirst();
        TreeNode rightNode = queue.pollLast();
        if (leftNode == null && rightNode == null) {
            continue;
        }
        if (leftNode == null || rightNode == null) {
            return false;
        }
        queue.addFirst(leftNode.right);
        queue.addFirst(leftNode.left);
        queue.addLast(rightNode.left);
        queue.addLast(rightNode.right);

        if (leftNode.val != rightNode.val) {
            return false;
        }
    }
    return true;
}
 
Example 11
Source File: LeetCode112.java    From Project with Apache License 2.0 5 votes vote down vote up
public boolean hasPathSum3(TreeNode root, int sum) {
    if (root != null) {
        LinkedList<TreeNode> nodeStack = new LinkedList();
        LinkedList<Integer> sumStack = new LinkedList();
        nodeStack.add(root);
        sumStack.add(sum - root.val);

        TreeNode node;
        int curSum;
        while (!nodeStack.isEmpty()) {
            node = nodeStack.pollLast();
            curSum = sumStack.pollLast();
            if ((node.right == null) && (node.left == null) && (curSum == 0)) {
                return true;
            }

            if (node.right != null) {
                nodeStack.add(node.right);
                sumStack.add(curSum - node.right.val);
            }
            if (node.left != null) {
                nodeStack.add(node.left);
                sumStack.add(curSum - node.left.val);
            }
        }
        return false;
    } else {
        return false;
    }
}
 
Example 12
Source File: LeetCode111.java    From Project with Apache License 2.0 5 votes vote down vote up
public int minDepth3(TreeNode root) {
    // Pair<key value>,表示一对值, List<pair<>> 近似可以理解为 map<>
    LinkedList<Pair<TreeNode, Integer>> stack = new LinkedList<>();
    if (root == null) {
        return 0;
    } else {
        // 根节点的高度设置为 1
        stack.add(new Pair(root, 1));
    }

    int minDepth = Integer.MAX_VALUE;
    while (!stack.isEmpty()) {
        // 弹出栈顶元素
        Pair<TreeNode, Integer> current = stack.pollLast();
        root = current.getKey();
        int currentDepth = current.getValue();
        if ((root.left == null) && (root.right == null)) {
            minDepth = Math.min(minDepth, currentDepth);
        }
        if (root.left != null) {
            stack.add(new Pair(root.left, currentDepth + 1));
        }
        if (root.right != null) {
            stack.add(new Pair(root.right, currentDepth + 1));
        }
    }
    return minDepth;
}
 
Example 13
Source File: LeetCode112.java    From Project with Apache License 2.0 5 votes vote down vote up
public boolean hasPathSum3(TreeNode root, int sum) {
    if (root != null) {
        LinkedList<TreeNode> nodeStack = new LinkedList();
        LinkedList<Integer> sumStack = new LinkedList();
        nodeStack.add(root);
        sumStack.add(sum - root.val);

        TreeNode node;
        int curSum;
        while (!nodeStack.isEmpty()) {
            node = nodeStack.pollLast();
            curSum = sumStack.pollLast();
            if ((node.right == null) && (node.left == null) && (curSum == 0)) {
                return true;
            }

            if (node.right != null) {
                nodeStack.add(node.right);
                sumStack.add(curSum - node.right.val);
            }
            if (node.left != null) {
                nodeStack.add(node.left);
                sumStack.add(curSum - node.left.val);
            }
        }
        return false;
    } else {
        return false;
    }
}
 
Example 14
Source File: LeetCode111.java    From Project with Apache License 2.0 5 votes vote down vote up
public int minDepth3(TreeNode root) {
    // Pair<key value>,表示一对值, List<pair<>> 近似可以理解为 map<>
    LinkedList<Pair<TreeNode, Integer>> stack = new LinkedList<>();
    if (root == null) {
        return 0;
    } else {
        // 根节点的高度设置为 1
        stack.add(new Pair(root, 1));
    }

    int minDepth = Integer.MAX_VALUE;
    while (!stack.isEmpty()) {
        // 弹出栈顶元素
        Pair<TreeNode, Integer> current = stack.pollLast();
        root = current.getKey();
        int currentDepth = current.getValue();
        if ((root.left == null) && (root.right == null)) {
            minDepth = Math.min(minDepth, currentDepth);
        }
        if (root.left != null) {
            stack.add(new Pair(root.left, currentDepth + 1));
        }
        if (root.right != null) {
            stack.add(new Pair(root.right, currentDepth + 1));
        }
    }
    return minDepth;
}
 
Example 15
Source File: LeetCode257.java    From Project with Apache License 2.0 5 votes vote down vote up
public List<String> binaryTreePaths2(TreeNode root) {
    LinkedList<String> paths = new LinkedList();
    if (root == null)
        return paths;

    LinkedList<TreeNode> node_stack = new LinkedList();
    LinkedList<String> path_stack = new LinkedList();
    node_stack.add(root);
    path_stack.add(Integer.toString(root.val));
    TreeNode node;
    String path;
    while (!node_stack.isEmpty()) {
        node = node_stack.pollLast();
        path = path_stack.pollLast();
        if ((node.left == null) && (node.right == null))
            paths.add(path);
        if (node.left != null) {
            node_stack.add(node.left);
            path_stack.add(path + "->" + Integer.toString(node.left.val));
        }
        if (node.right != null) {
            node_stack.add(node.right);
            path_stack.add(path + "->" + Integer.toString(node.right.val));
        }
    }
    return paths;
}
 
Example 16
Source File: GUIEditor.java    From niftyeditor with Apache License 2.0 5 votes vote down vote up
/**
 * move an element in points coordinates. 
 * @param to
 * @param from 
 */
public void move(Point2D to,final GElement from){
    if(from instanceof GLayer)
        return;
    this.setChanged();
    this.notifyObservers(new RemoveElementEvent(from));
    EndNotify callback = new EndNotify() {

        @Override
        public void perform() {
            GUIEditor.this.setChanged();
            GUIEditor.this.notifyObservers(new AddElementEvent(from));
            GUIEditor.this.selectElement(from);
            fireUpdate(from);
        }
    };
    LinkedList<GElement> elements = findAllElements(to);
    GElement ele = elements.pollLast();
    if(ele.equals(from)) {
        getGui().move(to,elements.pollLast(), from,callback);
    }
    else {
        getGui().move(to,ele,from,callback);
    }
   
   
    
}
 
Example 17
Source File: AllLessNumSubArray.java    From Project with Apache License 2.0 5 votes vote down vote up
/**
 * 使用双向最大最小值更新结构,时间复杂度为 O(N)
 */
public static int getNum(int[] arr, int num) {
    if (arr == null || arr.length == 0) {
        return 0;
    }
    // 分别准备最大值和最小值更新结构
    LinkedList<Integer> qmax = new LinkedList<Integer>();
    LinkedList<Integer> qmin = new LinkedList<Integer>();
    int L = 0;
    int R = 0;
    int res = 0;
    while (L < arr.length) {
        while (R < arr.length) {
            while (!qmin.isEmpty() && arr[qmin.peekLast()] >= arr[R]) {
                qmin.pollLast();
            }
            qmin.addLast(R);
            while (!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[R]) {
                qmax.pollLast();
            }
            qmax.addLast(R);
            // 不达标
            if (arr[qmax.getFirst()] - arr[qmin.getFirst()] > num) {
                break;
            }
            R++;
        }
        if (qmin.peekFirst() == L) {
            qmin.pollFirst();
        }
        if (qmax.peekFirst() == L) {
            qmax.pollFirst();
        }
        res += R - L;
        // 换一个开头
        L++;
    }
    return res;
}
 
Example 18
Source File: SyncService.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private LinkedList<BlockId> getBlockChainSummary(PeerConnection peer) throws Exception {

        BlockId beginBlockId = peer.getBlockBothHave();
        List<BlockId> blockIds = new ArrayList<>(peer.getSyncBlockToFetch());
        LinkedList<BlockId> forkList = new LinkedList<>();
        LinkedList<BlockId> summary = new LinkedList<>();
        long syncBeginNumber = gscNetDelegate.getSyncBeginNumber();
        long low = syncBeginNumber < 0 ? 0 : syncBeginNumber;
        long high;
        long highNoFork;

        if (beginBlockId.getNum() == 0) {
            highNoFork = high = gscNetDelegate.getHeadBlockId().getNum();
        } else {
            if (gscNetDelegate.containBlockInMainChain(beginBlockId)) {
                highNoFork = high = beginBlockId.getNum();
            } else {
                forkList = gscNetDelegate.getBlockChainHashesOnFork(beginBlockId);
                if (forkList.isEmpty()) {
                    throw new P2pException(TypeEnum.SYNC_FAILED,
                            "can't find blockId: " + beginBlockId.getString());
                }
                highNoFork = forkList.peekLast().getNum();
                forkList.pollLast();
                Collections.reverse(forkList);
                high = highNoFork + forkList.size();
            }
        }

        if (low > highNoFork) {
            throw new P2pException(TypeEnum.SYNC_FAILED, "low: " + low + " gt highNoFork: " + highNoFork);
        }

        long realHigh = high + blockIds.size();
        logger.info("Get block chain summary, low: {}, highNoFork: {}, high: {}, realHigh: {}",
                low, highNoFork, high, realHigh);

        while (low <= realHigh) {
            if (low <= highNoFork) {
                summary.offer(gscNetDelegate.getBlockIdByNum(low));
            } else if (low <= high) {
                summary.offer(forkList.get((int) (low - highNoFork - 1)));
            } else {
                summary.offer(blockIds.get((int) (low - high - 1)));
            }
            low += (realHigh - low + 2) / 2;
        }

        return summary;
    }
 
Example 19
Source File: ObservableSetMultimapTests.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void onChanged(
		org.eclipse.gef.common.collections.SetMultimapChangeListener.Change<? extends K, ? extends V> change) {
	if (keyQueue.size() <= 0) {
		fail("Received unexpected change " + change);
	}

	LinkedList<K> elementaryKeysQueue = keyQueue.pollLast();
	LinkedList<Set<V>> elementaryAddedValuesQueue = addedValuesQueue
			.pollLast();
	LinkedList<Set<V>> elementaryRemovedValuesQueue = removedValuesQueue
			.pollLast();

	assertEquals(source, change.getSetMultimap());

	StringBuffer expectedString = new StringBuffer();
	while (change.next()) {
		if (elementaryKeysQueue.size() <= 0) {
			fail("Did not expect another elementary change");
		}
		// check key
		K expectedKey = elementaryKeysQueue.pollLast();
		assertEquals(expectedKey, change.getKey());

		// check added values
		Set<V> expectedAddedValues = elementaryAddedValuesQueue
				.pollLast();
		assertEquals(expectedAddedValues, change.getValuesAdded());
		if (expectedAddedValues != null
				&& !expectedAddedValues.isEmpty()) {
			assertTrue(change.wasAdded());
		} else {
			assertFalse(change.wasAdded());
		}

		// check removed values
		Set<V> expectedRemovedValues = elementaryRemovedValuesQueue
				.pollLast();
		assertEquals(expectedRemovedValues, change.getValuesRemoved());
		if (expectedRemovedValues != null
				&& !expectedRemovedValues.isEmpty()) {
			assertTrue(change.wasRemoved());
		} else {
			assertFalse(change.wasRemoved());
		}

		// check string representation
		if (!expectedString.toString().isEmpty()) {
			expectedString.append(" ");
		}
		if (expectedAddedValues.isEmpty()
				&& !expectedRemovedValues.isEmpty()) {
			expectedString.append("Removed " + expectedRemovedValues
					+ " for key " + expectedKey + ".");
		} else if (!expectedAddedValues.isEmpty()
				&& expectedRemovedValues.isEmpty()) {
			expectedString.append("Added " + expectedAddedValues
					+ " for key " + expectedKey + ".");
		} else {
			expectedString.append("Replaced " + expectedRemovedValues
					+ " by " + expectedAddedValues + " for key "
					+ expectedKey + ".");
		}
	}
	if (elementaryKeysQueue.size() > 0) {
		fail("Did not receive " + elementaryKeysQueue.size()
				+ " expected elementary changes.");
	}
	assertEquals(expectedString.toString(), change.toString());
}
 
Example 20
Source File: ObservableMultisetTests.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void onChanged(
		org.eclipse.gef.common.collections.MultisetChangeListener.Change<? extends E> change) {
	if (elementQueue.size() <= 0) {
		fail("Received unexpected atomic change " + change);
	}

	LinkedList<E> elementaryElementsQueue = elementQueue.pollLast();
	LinkedList<Integer> elementaryAddedCountQueue = addedCountQueue
			.pollLast();
	LinkedList<Integer> elementaryRemovedCountQueue = removedCountQueue
			.pollLast();

	assertEquals(source, change.getMultiset());

	StringBuffer expectedString = new StringBuffer();
	while (change.next()) {
		if (elementaryElementsQueue.size() <= 0) {
			fail("Did not expect another elementary change");
		}
		// check element
		E expectedElement = elementaryElementsQueue.pollLast();
		assertEquals(expectedElement, change.getElement());

		// check added values
		int expectedAddCount = elementaryAddedCountQueue.pollLast();
		assertEquals(expectedAddCount, change.getAddCount());

		// check removed values
		int expectedRemoveCount = elementaryRemovedCountQueue
				.pollLast();
		assertEquals(expectedRemoveCount, change.getRemoveCount());

		// check string representation
		if (!expectedString.toString().isEmpty()) {
			expectedString.append(" ");
		}
		if (expectedAddCount > 0) {
			expectedString.append("Added " + expectedAddCount
					+ " occurrences of " + expectedElement + ".");
		} else {
			expectedString.append("Removed " + expectedRemoveCount
					+ " occurrences of " + expectedElement + ".");
		}
	}
	if (elementaryElementsQueue.size() > 0) {
		fail("Did not receive " + elementaryElementsQueue.size()
				+ " expected elementary changes.");
	}
	assertEquals(expectedString.toString(), change.toString());
}