Java Code Examples for java.util.Stack#isEmpty()
The following examples show how to use
java.util.Stack#isEmpty() .
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: ReferenceUtils.java From ghidra with Apache License 2.0 | 6 votes |
private static DataType findLeafDataType(DataType parent, Stack<String> path) { DataType baseParent = getBaseDataType(parent, true); if (path.isEmpty()) { return baseParent; // this must be the one } if (!(baseParent instanceof Composite)) { return null; } Composite composite = (Composite) baseParent; DataTypeComponent[] components = composite.getDefinedComponents(); String name = path.pop(); for (DataTypeComponent component : components) { if (component.getFieldName().equals(name)) { // found match--keep looking DataType newParent = component.getDataType(); return findLeafDataType(newParent, path); } } return null; }
Example 2
Source File: KeyFilesOperationsPgpImpl.java From pgptool with GNU General Public License v3.0 | 6 votes |
private void savePublicKey(Key key, OutputStream outputStream, boolean saveAsArmored) { Preconditions.checkArgument(key != null && key.getKeyData() != null && key.getKeyInfo() != null, "Key must be providedand fully described"); Stack<OutputStream> os = new Stack<>(); try { os.push(outputStream); if (saveAsArmored) { os.push(new ArmoredOutputStream(os.peek())); } KeyDataPgp keyDataPgp = KeyDataPgp.get(key); if (keyDataPgp.getPublicKeyRing() != null) { keyDataPgp.getPublicKeyRing().encode(os.peek()); } else { keyDataPgp.getSecretKeyRing().getPublicKey().encode(os.peek()); } } catch (Throwable t) { throw new RuntimeException("Failed to save public key " + key.getKeyInfo().getUser(), t); } finally { while (!os.isEmpty()) { IoStreamUtils.safeClose(os.pop()); } } }
Example 3
Source File: BinaryTree.java From POC with Apache License 2.0 | 6 votes |
public void traverseInOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current = root; stack.push(root); while (!stack.isEmpty()) { while (current.left != null) { current = current.left; stack.push(current); } current = stack.pop(); visit(current.value); if (current.right != null) { current = current.right; stack.push(current); } } }
Example 4
Source File: EditorUndoManagerImpl.java From incubator-retired-wave with Apache License 2.0 | 6 votes |
private FocusedRange restoreSelectionAfterUndoRedo(DocOp transformedNonUndoable, Stack<FocusedRange> selectionStack) { if (selectionStack.isEmpty()) { logger.log(Level.ERROR, "SelectionStack empty! This probably shouldn't be reached, but we can live with it."); return null; } FocusedRange selection = selectionStack.pop(); if (selection == UNKNOWN_SELECTION) { logger.log(Level.TRACE, "unknown selection"); return null; } else { if (transformedNonUndoable != null) { selection = RangeHelper.applyModifier(transformedNonUndoable, selection); } selectionHelper.setSelectionRange(selection); return selection; } }
Example 5
Source File: ExpressionParser.java From hbase with Apache License 2.0 | 6 votes |
private void processNOTOp(Stack<ExpressionNode> expStack, String expS, int index) throws ParseException { // When ! comes, the stack can be empty or top ( or top can be some exp like // a& // !!.., a!, a&b!, !a! are invalid if (!expStack.isEmpty()) { ExpressionNode top = expStack.peek(); if (top.isSingleNode() && top != LeafExpressionNode.OPEN_PARAN_NODE) { throw new ParseException("Error parsing expression " + expS + " at column : " + index); } if (!top.isSingleNode() && ((NonLeafExpressionNode) top).getChildExps().size() != 1) { throw new ParseException("Error parsing expression " + expS + " at column : " + index); } } expStack.push(new NonLeafExpressionNode(Operator.NOT)); }
Example 6
Source File: Main5.java From cs-summary-reflection with Apache License 2.0 | 6 votes |
public static boolean istrue(String s) { char[] c = s.toCharArray(); Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < c.length; i++) { if (stack.isEmpty()) { if (c[i] == '(') stack.push(c[i]); else { return false; } } else { if (c[i] == ')') stack.pop(); else stack.push(c[i]); } } if (stack.size() == 0) return true; else return false; }
Example 7
Source File: Solution.java From LeetCode-Solution-in-Good-Style with Apache License 2.0 | 5 votes |
public String removeDuplicateLetters(String s) { int len = s.length(); // 预处理,我把一个字符出现的最后一个位置记录下来 Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < len; i++) { map.put(s.charAt(i), i); } // 保存已经出现过的 Set<Character> set = new HashSet<>(); Stack<Character> stack = new Stack<>(); for (int i = 0; i < len; i++) { Character curChar = s.charAt(i); if (set.contains(curChar)) { continue; } // 注意:这里条件判断语句很长,map.get(stack.peek()) 不要写成了 map.get(curChar) while (!stack.isEmpty() && map.get(stack.peek()) > i && curChar < stack.peek()) { // 出栈的同时,也要从哈希表中移除 set.remove(stack.pop()); } stack.push(curChar); set.add(curChar); } StringBuilder stringBuilder = new StringBuilder(); while (!stack.isEmpty()) { stringBuilder.insert(0, stack.pop()); } return stringBuilder.toString(); }
Example 8
Source File: BraceMatchingUtilAdapter.java From HighlightBracketPair with Apache License 2.0 | 5 votes |
/** * find the right closest brace offset position * * @param iterator highlight iterator * @param rparenTokenType right token type to paired * @param fileText file text * @param fileType file type * @return offset */ public static int findRightRParen(HighlighterIterator iterator, IElementType rparenTokenType, CharSequence fileText, FileType fileType, boolean isBlockCaret) { int lastRbraceOffset = -1; int initOffset = iterator.atEnd() ? -1 : iterator.getStart(); Stack<IElementType> braceStack = new Stack<>(); for (; !iterator.atEnd(); iterator.advance()) { final IElementType tokenType = iterator.getTokenType(); if (isRBraceToken(iterator, fileText, fileType)) { if (!braceStack.isEmpty()) { IElementType topToken = braceStack.pop(); if (!isPairBraces(tokenType, topToken, fileType)) { break; // unmatched braces } } else { if (tokenType == rparenTokenType) { return iterator.getStart(); } else { break; } } } else if (isLBraceToken(iterator, fileText, fileType)) { if (isBlockCaret && initOffset == iterator.getStart()) continue; else braceStack.push(iterator.getTokenType()); } } return lastRbraceOffset; }
Example 9
Source File: JoinOrderQueryConversionVisitor.java From reladomo with Apache License 2.0 | 5 votes |
public JoinNode getJoinTree() { JoinNode root = null; HashSet<String> alreadyProcessed = new HashSet<String>(); Stack<JoinNode> toFollow = new Stack<JoinNode>(); root = createFirstJoinNode(root, alreadyProcessed, toFollow); while(!toFollow.isEmpty() && !this.joins.isEmpty()) { JoinNode currentRoot = toFollow.pop(); for(Iterator it = this.joins.iterator(); it.hasNext(); ) { Join join = (Join) it.next(); if (join.hasObject(currentRoot.getLeft())) { it.remove(); join.alignToLeft(currentRoot.getLeft()); if (alreadyProcessed.contains(join.getRight().getClassName())) { throw new RuntimeException("Triangluar relationship not supported, in relationship "+relationshipAttribute.getName()+" in object "+ relationshipAttribute.getFromObject().getClassName()+" joining "+join.getLeft().getClassName()+" and "+ join.getRight().getClassName()); } toFollow.push(currentRoot.addRight(join.getRight(), relationshipAttribute)); alreadyProcessed.add(join.getRight().getClassName()); } } } root.reorder(relationshipAttribute.getRelatedObject()); return root; }
Example 10
Source File: VariableScope.java From swift-k with Apache License 2.0 | 5 votes |
private void undeclare(Map<String, Stack<Usage>> access, String name) throws CompilationException { Stack<Usage> s = access.get(name); if (s == null || s.isEmpty()) { throw new RuntimeException("Mistmatched undeclare for " + name + " in scope " + this); } Usage u = s.pop(); if (s.isEmpty()) { access.remove(name); } if (u.lastReader != null && u.lastWriter == null) { throw new CompilationException("Uninitialized variable: " + name); } }
Example 11
Source File: BST.java From java-technology-stack with MIT License | 5 votes |
public void preOrderNR(){ Stack<Node> stack = new Stack<>(); stack.push(root); while(!stack.isEmpty()){ Node cur = stack.pop(); System.out.println(cur.e); if(cur.right != null) stack.push(cur.right); if(cur.left != null) stack.push(cur.left); } }
Example 12
Source File: NonRecursiveInOrderTreeWalk.java From cs-review with MIT License | 5 votes |
@SuppressWarnings("unchecked") @Override public <C extends TreeWalkCallback<E, N>> C perform(N root, C callback) { if (root == null) { return null; } final Stack<N> stack = new Stack<>(); N current = root; boolean popped = false; do { if (current.getLeftChild() == null || popped) { callback.apply(current); if (current.getRightChild() != null) { current = (N) current.getRightChild(); popped = false; } else if (!stack.isEmpty()) { current = stack.pop(); popped = true; } else { break; } } else { stack.push(current); current = (N) current.getLeftChild(); popped = false; } } while (true); return callback; }
Example 13
Source File: TraceEventRecords2ExecutionAndMessageTraceFilter.java From kieker with Apache License 2.0 | 5 votes |
/** * Finished the current execution. All open executions are finished and correctly added (if possible). * * @throws InvalidTraceException */ public void finish() throws InvalidTraceException { final Stack<AbstractTraceEvent> tmpEventStack = new Stack<>(); final Stack<ExecutionInformation> tmpExecutionStack = new Stack<>(); if (!this.eventStack.isEmpty()) { final long lastTimeStamp = this.eventStack.peek().getTimestamp(); while (!this.eventStack.isEmpty()) { // reverse order tmpEventStack.push(this.eventStack.pop()); tmpExecutionStack.push(this.executionStack.pop()); } while (!tmpEventStack.isEmpty()) { // create executions (in reverse order) final AbstractTraceEvent currentEvent = tmpEventStack.pop(); final ExecutionInformation executionInformation = tmpExecutionStack.pop(); if (currentEvent instanceof CallOperationEvent) { this.finishExecution( ((CallOperationEvent) currentEvent).getCalleeOperationSignature(), ((CallOperationEvent) currentEvent).getCalleeClassSignature(), this.trace.getTraceId(), this.trace.getSessionId(), this.trace.getHostname(), executionInformation.getEoi(), executionInformation.getEss(), currentEvent.getTimestamp(), lastTimeStamp, !this.ignoreAssumedCalls, currentEvent instanceof CallConstructorEvent); } else { throw new InvalidTraceException("Only CallOperationEvents are expected to be remaining, but found: " + currentEvent.getClass().getSimpleName()); } } } }
Example 14
Source File: ReverseStackUsingRecursive.java From Project with Apache License 2.0 | 5 votes |
/** * 每层递归取出栈底的元素并缓存到变量中,直到栈空; * 然后逆向将每层变量压入栈,最后实现原栈数据的逆序。 * * @param stack */ public static void reverse(Stack<Integer> stack) { if (stack.isEmpty()) { return; } // 依次返回1、2、3 int i = getAndRemoveLastElement(stack); reverse(stack); // 依次压入3、2、1 stack.push(i); }
Example 15
Source File: Solution6.java From LeetCode-Solution-in-Good-Style with Apache License 2.0 | 5 votes |
public int largestRectangleArea(int[] heights) { int len = heights.length; // 2 个哨兵 int[] newHeights = new int[len + 2]; System.arraycopy(heights, 0, newHeights, 1, len); // 添加哨兵 1:它永远在 newHeights[0] = -1; // 添加哨兵 2:它进去了也没有机会出来了 newHeights[len + 1] = 0; // 为了易于编码,将 heights 指向 newHeights heights = newHeights; len += 2; Stack<Integer> stack = new Stack<>(); int maxAres = 0; for (int i = 0; i < len; i++) { // 注意:这里是 while while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) { int currentIndex = stack.pop(); // 因为有 -1 在 stack.peek() 永远非空 int width = i - stack.peek() - 1;; maxAres = Math.max(maxAres, heights[currentIndex] * width); } stack.push(i); } return maxAres; }
Example 16
Source File: BaseSite.java From sakai with Educational Community License v2.0 | 4 votes |
/** * {@inheritDoc} */ public Element toXml(Document doc, Stack stack) { Element site = doc.createElement("site"); if (stack.isEmpty()) { doc.appendChild(site); } else { ((Element) stack.peek()).appendChild(site); } site.setAttribute("id", getId()); if (m_title != null) site.setAttribute("title", m_title); // encode the short description if (m_shortDescription != null) Xml.encodeAttribute(site, "short-description-enc", m_shortDescription); // encode the description if (m_description != null) Xml.encodeAttribute(site, "description-enc", m_description); site.setAttribute("joinable", Boolean.valueOf(m_joinable).toString()); if (m_joinerRole != null) site.setAttribute("joiner-role", m_joinerRole); site.setAttribute("published", Boolean.valueOf(m_published).toString()); if (m_icon != null) site.setAttribute("icon", m_icon); if (m_info != null) site.setAttribute("info", m_info); if (m_skin != null) site.setAttribute("skin", m_skin); site.setAttribute("pubView", Boolean.valueOf(m_pubView).toString()); site.setAttribute("customPageOrdered", Boolean.valueOf(m_customPageOrdered) .toString()); site.setAttribute("type", m_type); site.setAttribute("created-id", m_createdUserId); site.setAttribute("modified-id", m_lastModifiedUserId); site.setAttribute("created-time", m_createdTime.toString()); site.setAttribute("modified-time", m_lastModifiedTime.toString()); // properties stack.push(site); getProperties().toXml(doc, stack); stack.pop(); // site pages Element list = doc.createElement("pages"); site.appendChild(list); stack.push(list); for (Iterator iPages = getPages().iterator(); iPages.hasNext();) { BaseSitePage page = (BaseSitePage) iPages.next(); page.toXml(doc, stack); } stack.pop(); // TODO: site groups return site; }
Example 17
Source File: ContextTransitionTable.java From vasco with GNU Lesser General Public License v2.1 | 4 votes |
/** * Computes a reachable set of value contexts from a particular * source by traversing the context transition table. * * Note that the source context itself is only reachable from * itself if it there is a recursive call to it (i.e. a context * is not reachable to itself by default). * * @param source the source context * @return a set of contexts reachable from <tt>source</tt> */ public Set<Context<M,N,A>> reachableSet(Context<M,N,A> source, boolean ignoreFree) { // The result set Set<Context<M,N,A>> reachableContexts = new HashSet<Context<M,N,A>>(); // Maintain a stack of contexts to process Stack<Context<M,N,A>> stack = new Stack<Context<M,N,A>>(); // Initialise it with the source stack.push(source); // Now recursively (using stacks) mark reachable contexts while (stack.isEmpty() == false) { // Get the next item to process source = stack.pop(); // Add successors if (callSitesOfContexts.containsKey(source)) { // The above check is there because methods with no calls have no entry for (CallSite<M,N,A> callSite : callSitesOfContexts.get(source)) { // Don't worry about DEFAULT edges if (defaultCallSites.contains(callSite)) { continue; } for (M method : transitions.get(callSite).keySet()) { Context<M,N,A> target = transitions.get(callSite).get(method); // Don't process the same element twice if (reachableContexts.contains(target) == false) { // Are we ignoring free contexts? if (ignoreFree && target.isFreed()) { continue; } // Mark reachable reachableContexts.add(target); // Add it's successors also later stack.push(target); } } } } } return reachableContexts; }
Example 18
Source File: EqualStacks.java From Hackerrank-Solutions with MIT License | 4 votes |
static int equalStacks(int[] h1, int[] h2, int[] h3) { Stack<Integer> st1 = new Stack<Integer>(); Stack<Integer> st2 = new Stack<Integer>(); Stack<Integer> st3 = new Stack<Integer>(); int st1TotalHeight = 0, st2TotalHeight = 0, st3TotalHeight = 0; // pushing consolidated height into the stack instead of individual cylinder // height for (int i = h1.length - 1; i >= 0; i--) { st1TotalHeight += h1[i]; st1.push(st1TotalHeight); } for (int i = h2.length - 1; i >= 0; i--) { st2TotalHeight += h2[i]; st2.push(st2TotalHeight); } for (int i = h3.length - 1; i >= 0; i--) { st3TotalHeight += h3[i]; st3.push(st3TotalHeight); } while (true) { // If any stack is empty if (st1.isEmpty() || st2.isEmpty() || st3.isEmpty()) return 0; st1TotalHeight = st1.peek(); st2TotalHeight = st2.peek(); st3TotalHeight = st3.peek(); // If sum of all three stack are equal. if (st1TotalHeight == st2TotalHeight && st2TotalHeight == st3TotalHeight) return st1TotalHeight; // Finding the stack with maximum sum and // removing its top element. if (st1TotalHeight >= st2TotalHeight && st1TotalHeight >= st3TotalHeight) st1.pop(); else if (st2TotalHeight >= st1TotalHeight && st2TotalHeight >= st3TotalHeight) st2.pop(); else if (st3TotalHeight >= st2TotalHeight && st3TotalHeight >= st1TotalHeight) st3.pop(); } }
Example 19
Source File: Post.java From sakai with Educational Community License v2.0 | 4 votes |
/** * @see org.sakaiproject.entity.api.Entity#toXml() * * @return */ public Element toXml(Document doc, Stack stack) { Element postElement = doc.createElement(XmlDefs.POST); if (stack.isEmpty()) { doc.appendChild(postElement); } else { ((Element) stack.peek()).appendChild(postElement); } stack.push(postElement); Element idElement = doc.createElement(XmlDefs.ID); idElement.setTextContent(id); postElement.appendChild(idElement); Element createdDateElement = doc.createElement(XmlDefs.CREATEDDATE); createdDateElement.setTextContent(Long.toString(createdDate)); postElement.appendChild(createdDateElement); Element modifiedDateElement = doc.createElement(XmlDefs.MODIFIEDDATE); modifiedDateElement.setTextContent(Long.toString(modifiedDate)); postElement.appendChild(modifiedDateElement); Element creatorIdElement = doc.createElement(XmlDefs.CREATORID); creatorIdElement.setTextContent(creatorId); postElement.appendChild(creatorIdElement); Element contentElement = doc.createElement(XmlDefs.CONTENT); contentElement.setTextContent(wrapWithCDATA(content)); postElement.appendChild(contentElement); if (comments.size() > 0) { Element commentsElement = doc.createElement(XmlDefs.COMMENTS); for (Comment comment : comments) { Element commentElement = doc.createElement(XmlDefs.COMMENT); commentElement.setAttribute(XmlDefs.ID, comment.getId()); commentElement.setAttribute(XmlDefs.CREATORID, comment.getCreatorId()); commentElement.setAttribute(XmlDefs.CREATEDDATE, Long.toString(comment.getCreatedDate())); commentElement.setAttribute(XmlDefs.MODIFIEDDATE, Long.toString(comment.getModifiedDate())); commentElement.setTextContent(wrapWithCDATA(comment.getContent())); commentsElement.appendChild(commentElement); } postElement.appendChild(commentsElement); } stack.pop(); return postElement; }
Example 20
Source File: LastGroupSeparator.java From pcgen with GNU Lesser General Public License v2.1 | 4 votes |
public String process() { StringTokenizer base = new StringTokenizer(startingString, "()", true); int sbLength = startingString.length(); root = new StringBuilder(sbLength); StringBuilder temp = new StringBuilder(sbLength); boolean isValid = false; Stack<String> expected = new Stack<>(); while (base.hasMoreTokens()) { String working = base.nextToken(); if (expected.isEmpty()) { if (isValid) { root.append('('); root.append(temp); root.append(')'); } temp = new StringBuilder(sbLength); isValid = false; } if ("(".equals(working)) { if (!expected.isEmpty()) { temp.append(working); } isValid = true; expected.push(")"); } else if (")".equals(working)) { if (expected.isEmpty()) { throw new GroupingMismatchException( startingString + " did not have an open parenthesis " + "before close: " + temp); } else if (!")".equals(expected.pop())) { throw new GroupingMismatchException( startingString + " did not have matching parenthesis " + "inside of brackets: " + temp); } else if (!expected.isEmpty()) { temp.append(working); } } else if (expected.isEmpty()) { root.append(working); } else { temp.append(working); } } if (expected.isEmpty()) { if (!isValid) { return null; } return temp.toString(); } throw new GroupingMismatchException( startingString + " reached end of String while attempting to match: " + expected.pop()); }