下面列出了java.util.LinkedList#pollFirst ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static int getNum(LinkedList<String> que) {
int res = 0;
boolean add = true;
String cur = null;
int num = 0;
while (!que.isEmpty()) {
cur = que.pollFirst();
if (cur.equals("+")) {
add = true;
} else if (cur.equals("-")) {
add = false;
} else {
num = Integer.valueOf(cur);
res += add ? num : (-num);
}
}
return res;
}
public void dump(ByteBuf buffer, Map<String, PullLogIndexEntry> indexMap) {
for (Map.Entry<String, PullLogSequence> entry : messageSequences.entrySet()) {
LinkedList<Range> messagesInRange = entry.getValue().messagesInRange;
Range first = messagesInRange.pollFirst();
if (first == null) continue;
long baseMessageSequence = first.start;
PullLogIndexEntry indexEntry = new PullLogIndexEntry(entry.getValue().basePullSequence, baseMessageSequence, buffer.writerIndex(), messagesInRange.size());
indexMap.put(entry.getKey(), indexEntry);
for (Range range : messagesInRange) {
for (long i = range.start; i <= range.end; ++i) {
buffer.writeInt((int) (i - baseMessageSequence));
}
}
}
}
public static Set<Long> get_all_children(Joern_db joern_db, Long node_id)
{
Set<Long> children = new HashSet<>();
LinkedList<Long> new_nodes = new LinkedList<>();
new_nodes.add(node_id);
while(!new_nodes.isEmpty())
{
Long cur = new_nodes.pollFirst();
List<Node> its_children = Pipeline.v(cur).children().to_list();
for(Node c : its_children)
{
if(children.contains(c.getId()))
{
continue;
}
new_nodes.add(c.getId());
children.add(c.getId());
}
}
return children;
}
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;
}
/**
* 使用双向最大最小值更新结构,时间复杂度为 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;
}
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k < 1 || nums.length < k) {
return new int[0];
}
LinkedList<Integer> maxList = new LinkedList<Integer>();
int[] res = new int[nums.length - k + 1];
int index = 0;
for (int i = 0; i < nums.length; i++) {
// 更新双端队列,如果双端队列不为空,并且尾结点(存的是下标)对应数组中的值是否小于等于当前值
while (!maxList.isEmpty() && nums[maxList.peekLast()] <= nums[i]) {
maxList.pollLast();
}
// 上面一直弹出,直到不符合然后加上当前值。
maxList.addLast(i);
// 上面加法是通用的,但是减法是针对该题定制的
// 当过期的时候(当窗口形成之后再扩充才算过期)即窗口长度 > k,窗口形成过程中不会过期, i - k 表示过期的下标
if (maxList.peekFirst() == i - k) {
maxList.pollFirst();
}
// 判断下标过期
if (i >= k - 1) {
// 当窗口已经形成了,记录每一步的res
res[index++] = nums[maxList.peekFirst()];
}
}
return res;
}
@Override
public <E> Iterator<E> iterator(Class<E> clazz, InputStream stream) {
// 实例列表
HashMap<Object, E> instanceObjects = new HashMap<>();
try {
Properties properties = new Properties();
properties.load(stream);
Constructor<E> constructor = clazz.getDeclaredConstructor();
ReflectionUtility.makeAccessible(constructor);
Field storageId = ReflectionUtility.uniqueField(clazz, ResourceId.class);
storageId.setAccessible(true);
TreeMap<?, ?> keyValues = new TreeMap<>(properties);
for (Entry<?, ?> keyValue : keyValues.entrySet()) {
LinkedList<String> fieldNames = new LinkedList<>(Arrays.asList(String.class.cast(keyValue.getKey()).split(dot)));
String fieldName = fieldNames.pollFirst();
String fieldValue = String.class.cast(keyValue.getValue());
Object instanceId = ConversionUtility.convert(fieldName, storageId.getGenericType());
E instanceObject = instanceObjects.get(instanceId);
if (instanceObject == null) {
instanceObject = constructor.newInstance();
storageId.set(instanceObject, instanceId);
instanceObjects.put(instanceId, instanceObject);
}
if (fieldNames.isEmpty()) {
continue;
} else {
fieldName = fieldNames.pollFirst();
process(instanceObject, clazz, fieldName, fieldNames, fieldValue);
}
}
return instanceObjects.values().iterator();
} catch (Exception exception) {
throw new StorageException("遍历Properties异常", exception);
}
}
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;
}
private static void generateJson(LinkedList<String> arguments) throws ClassNotFoundException, IOException {
String catName = arguments.pollFirst();
String className = arguments.pollFirst();
String storedPath = arguments.pollFirst();
File storeDir = new File(storedPath);
ThriftType.StructType structType = ThriftSchemaConverter.toStructType((Class<? extends TBase<?, ?>>) Class.forName(className));
ObjectMapper mapper = new ObjectMapper();
String fileName = catName + ".json";
mapper.writerWithDefaultPrettyPrinter().writeValue(new File(storeDir, fileName), structType);
}
/**
* スタックから先頭の値を取り出す。
* @param stack
* @return スタックが空の場合は空文字を返す。
*/
public static String popup(final LinkedList<String> stack) {
if(stack.isEmpty()) {
return "";
}
return stack.pollFirst();
}
static private boolean processInheritors(final String qName, final PsiElement context, final Processor<? super PsiElement> consumer) {
final Set<String> namesSet = new THashSet<String>();
final LinkedList<String> namesQueue = new LinkedList<String>();
namesQueue.add(qName);
final Project project = context.getProject();
final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
while (!namesQueue.isEmpty()) {
final String name = namesQueue.pollFirst();
if (!namesSet.add(name)) {
continue;
}
List<List<HaxeClassInfo>> files = FileBasedIndex.getInstance().getValues(HaxeInheritanceIndex.HAXE_INHERITANCE_INDEX, name, scope);
files.addAll(FileBasedIndex.getInstance().getValues(HaxeTypeDefInheritanceIndex.HAXE_TYPEDEF_INHERITANCE_INDEX, name, scope));
for (List<HaxeClassInfo> subClassInfoList : files) {
for (HaxeClassInfo subClassInfo : subClassInfoList) {
final HaxeClass subClass = HaxeResolveUtil.findClassByQName(subClassInfo.getValue(), context.getManager(), scope);
if (subClass != null) {
if (!consumer.process(subClass)) {
return true;
}
namesQueue.add(subClass.getQualifiedName());
}
}
}
}
return true;
}
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();
}
public static void BFSExplore(LinkedList< Integer >[] adjacencyList, LinkedList<Integer> queue, int[] parent) {
if (queue.isEmpty()) {
return;
}
int vertex = queue.pollFirst();
System.out.println("vertex = " + vertex);
for (int adjacentVertex : adjacencyList[vertex]) {
if (parent[adjacentVertex] == Integer.MAX_VALUE) { // if parent is not set, it is unvisited
parent[adjacentVertex] = vertex;
queue.add(adjacentVertex);
}
}
}
public CleanerConfig verify() throws RuntimeException {
final LinkedList<RuntimeException> result = new LinkedList<>();
if (getTenantId() == null) {
result.add(missingField("tenantId"));
}
if (this.infinispan.getHost().isBlank()) {
result.add(missingField("infinispan.host"));
}
if (this.infinispan.getPort() <= 0) {
result.add(missingField("infinispan.port"));
}
if (this.infinispan.getCacheNames().getDevices().isBlank()) {
result.add(missingField("infinispan.devicesCacheName"));
}
if (this.infinispan.getCacheNames().getDeviceConnections().isBlank()) {
result.add(missingField("infinispan.deviceStatesCacheName"));
}
// create result
final RuntimeException e = result.pollFirst();
if (e != null) {
result.forEach(e::addSuppressed);
throw e;
}
return this;
}
protected static void closeEntries ( final List<ImportEntry> entries ) throws Exception
{
final LinkedList<Exception> errors = new LinkedList<> ();
// close all
for ( final ImportEntry entry : entries )
{
try
{
entry.close ();
}
catch ( final Exception e )
{
errors.add ( e );
}
}
// throw later
if ( !errors.isEmpty () )
{
final Exception first = errors.pollFirst ();
for ( final Exception ex : errors )
{
first.addSuppressed ( ex );
}
throw first;
}
}
/**
* スタックから先頭の値を取り出す。
* @param stack
* @return スタックが空の場合は空文字を返す。
*/
public static String popup(final LinkedList<String> stack) {
if(stack.isEmpty()) {
return "";
}
return stack.pollFirst();
}
public static void main(String[] args) throws Exception {
LinkedList<String> arguments = new LinkedList<String>(Arrays.asList(args));
String operator = arguments.pollFirst();
if (operator.equals("generate-json")) {
//java CompatibilityRunner generate-json tfe_request com.twitter.logs.TfeRequestLog old_json/
generateJson(arguments);
}
if (operator.equals("compare-json")) {
compareJson(arguments);
}
}
private static void compareJson(LinkedList<String> arguments) throws IOException {
String oldJsonPath = arguments.pollFirst();
String newJsonPath = arguments.pollFirst();
File oldJsonFile = new File(oldJsonPath);
checkExist(oldJsonFile);
File newJsonFile = new File(newJsonPath);
checkExist(newJsonFile);
ObjectMapper mapper = new ObjectMapper();
ThriftType.StructType oldStruct = mapper.readValue(oldJsonFile, ThriftType.StructType.class);
ThriftType.StructType newStruct = mapper.readValue(newJsonFile, ThriftType.StructType.class);
CompatibilityReport report = new CompatibilityChecker().checkCompatibility(oldStruct, newStruct);
if (!report.isCompatible) {
System.err.println("schema not compatible");
System.err.println(report.getMessages());
System.exit(1);
}
if (report.hasEmptyStruct()) {
System.err.println("schema contains empty struct");
System.err.println(report.getMessages());
System.exit(1);
}
System.out.println("[success] schema is compatible");
}
/**
* Does a 'breadth first' search of ancestors, caching as it goes
* @param nodeIds initial list of nodes to visit
* @return all visited nodes, in no particular order
*/
private List<Long> cacheAncestors(List<Long> nodeIds)
{
final LinkedList<Long> toVisit = new LinkedList<Long>(nodeIds);
Set<Long> visited = new TreeSet<Long>();
Long nodeId;
nodeDAO.cacheNodesById(toVisit);
Long lastCached = toVisit.peekLast();
while ((nodeId = toVisit.pollFirst()) != null)
{
if (visited.add(nodeId) && (nodeDAO.getNodeIdStatus(nodeId) != null) && (false == nodeDAO.getNodeIdStatus(nodeId).isDeleted()))
{
nodeDAO.getParentAssocs(nodeId, null, null, null, new ChildAssocRefQueryCallback()
{
@Override
public boolean preLoadNodes()
{
return false;
}
@Override
public boolean orderResults()
{
return false;
}
@Override
public boolean handle(Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair, Pair<Long, NodeRef> childNodePair)
{
toVisit.add(parentNodePair.getFirst());
return true;
}
@Override
public void done()
{
}
});
}
final boolean nodeIdEqualsLastCached = (nodeId == null && lastCached == null) ||
(nodeId != null && nodeId.equals(lastCached));
if (nodeIdEqualsLastCached && !toVisit.isEmpty())
{
nodeDAO.cacheNodesById(toVisit);
lastCached = toVisit.peekLast();
}
}
return new ArrayList<Long>(visited);
}
public void timingCompress() throws RuntimeException {
LinkedList<CleanupRecord> removedList = new LinkedList<CleanupRecord>();
CleanupRecord lastEnabledRecord = null;
for (int current = CONSTANTS_START_INDEX; current < this.endIndex; current = current + CONSTANTS_RECORD_SIZE + 1) {
int index = (current - CONSTANTS_START_INDEX) / (CONSTANTS_RECORD_SIZE + 1);
CleanupRecord record = this.recordList.get(index);
int memoRecordFlag = record.getRecordFlag();
boolean memoEnabled = record.isEnabled();
boolean forgetFlag = (memoRecordFlag & 0x2) == 0x2;
if (memoEnabled && forgetFlag) {
this.delete(record); // change status & unRegister record
removedList.add(record);
continue;
} else if (memoEnabled == false) {
removedList.add(record);
this.unRegisterRecord(record); // unRegister record
continue;
}
CleanupRecord removedRecord = removedList.pollFirst();
if (removedRecord == null) {
lastEnabledRecord = record;
continue;
}
removedRecord.setEnabled(record.isEnabled());
removedRecord.setRecordFlag(record.getRecordFlag());
removedRecord.setResource(record.getResource());
// removedRecord.setStartIndex(); // dont set startIndex
removedRecord.setXid(record.getXid());
this.forget(removedRecord);
this.delete(record);
removedList.add(record);
lastEnabledRecord = removedRecord;
} // end-for
int lastRecordEndIndex = lastEnabledRecord == null ? //
CONSTANTS_START_INDEX : lastEnabledRecord.getStartIndex() + CONSTANTS_RECORD_SIZE + 1;
this.updateEndIndex(lastRecordEndIndex);
}