java.util.Stack Java Examples

The following examples show how to use java.util.Stack. 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 Project: rapidminer-studio   Author: rapidminer   File: BallTree.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private void traverseTree(Stack<BallTreeNode<T>> stack, Stack<Integer> sideStack, BallTreeNode<T> root, double[] values) {
	BallTreeNode<T> currentNode = root;
	stack.push(currentNode);
	while (!currentNode.isLeaf()) {
		if (currentNode.hasTwoChilds()) {
			double distanceLeft = distance.calculateDistance(currentNode.getLeftChild().getCenter(), values);
			double distanceRight = distance.calculateDistance(currentNode.getRightChild().getCenter(), values);
			currentNode = (distanceLeft < distanceRight) ? currentNode.getLeftChild() : currentNode.getRightChild();
			sideStack.push(Double.compare(distanceLeft, distanceRight));
		} else {
			currentNode = currentNode.getChild();
			sideStack.push(0);
		}
		stack.push(currentNode);
	}
	sideStack.push(0);
}
 
Example #2
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: NamespaceMappings.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Declare a mapping of a prefix to namespace URI at the given element depth.
 * @param prefix a String with the prefix for a qualified name
 * @param uri a String with the uri to which the prefix is to map
 * @param elemDepth the depth of current declaration
 */
boolean pushNamespace(String prefix, String uri, int elemDepth)
{
    // Prefixes "xml" and "xmlns" cannot be redefined
    if (prefix.startsWith(XML_PREFIX))
    {
        return false;
    }

    Stack stack;
    // Get the stack that contains URIs for the specified prefix
    if ((stack = (Stack) m_namespaces.get(prefix)) == null)
    {
        m_namespaces.put(prefix, stack = new Stack());
    }

    if (!stack.empty() && uri.equals(((MappingRecord)stack.peek()).m_uri))
    {
        return false;
    }
    MappingRecord map = new MappingRecord(prefix,uri,elemDepth);
    stack.push(map);
    m_nodeStack.push(map);
    return true;
}
 
Example #3
/**
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 * Runtime: <a href="https://leetcode.com/submissions/detail/248556303/">1 ms</a>.
 * @param root
 * @return
 */
public static int findSecondMinimumValueIterative(TreeNode root) {
    if (root == null || (root.left == null && root.right == null)) return -1;

    int min = root.val;
    long secondMin = Long.MAX_VALUE;

    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);

    while (!stack.empty()) {
        TreeNode node = stack.pop();
        if (node == null) continue;

        if (node.val > min && node.val < secondMin) {
            secondMin = node.val;
        }
        stack.push(node.left);
        stack.push(node.right);
    }

    return secondMin == Long.MAX_VALUE ? -1 : (int) secondMin;
}
 
Example #4
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: NamespaceMappings.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Declare a mapping of a prefix to namespace URI at the given element depth.
 * @param prefix a String with the prefix for a qualified name
 * @param uri a String with the uri to which the prefix is to map
 * @param elemDepth the depth of current declaration
 */
boolean pushNamespace(String prefix, String uri, int elemDepth)
{
    // Prefixes "xml" and "xmlns" cannot be redefined
    if (prefix.startsWith(XML_PREFIX))
    {
        return false;
    }

    Stack stack;
    // Get the stack that contains URIs for the specified prefix
    if ((stack = (Stack) m_namespaces.get(prefix)) == null)
    {
        m_namespaces.put(prefix, stack = new Stack());
    }

    if (!stack.empty() && uri.equals(((MappingRecord)stack.peek()).m_uri))
    {
        return false;
    }
    MappingRecord map = new MappingRecord(prefix,uri,elemDepth);
    stack.push(map);
    m_nodeStack.push(map);
    return true;
}
 
Example #5
Source Project: toothpick   Author: stephanenicolas   File: ScopeTestUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Scope findRandomNode(Object rooScopeName, int acceptanceThreshold) {
  ScopeNode root = (ScopeNode) Toothpick.openScope(rooScopeName);
  ScopeNode result = null;
  Stack<ScopeNode> scopeStack = new Stack<>();
  scopeStack.push(root);
  while (result == null && !scopeStack.isEmpty()) {
    ScopeNode scope = scopeStack.pop();
    if (RANDOM.nextInt(RANDOM_INTERVAL_LENGTH) < acceptanceThreshold && scope != root) {
      result = scope;
    } else {
      for (ScopeNode childScope : scope.getChildrenScopes()) {
        scopeStack.push(childScope);
      }
    }
  }
  return result;
}
 
Example #6
Source Project: coderadar   Author: adessoAG   File: Node.java    License: MIT License 6 votes vote down vote up
/**
 * Traverse the Tree in post order. Call method in TraverseInterface for every found Node-object.
 *
 * @param traverseInterface method to call.
 */
public void traversePost(TraverseInterface traverseInterface) {
  Stack<Node> stack = new Stack<>();
  HashSet<Node> hash = new HashSet<>();
  Node root = this;
  stack.push(root);
  while (!stack.isEmpty()) {
    root = stack.peek();
    if (root.children.size() == 0 || hash.contains(root)) {
      traverseInterface.traverseMethod(stack.pop());
    } else {
      root.children.forEach(stack::push);
      hash.add(root);
    }
  }
}
 
Example #7
Source Project: awesome-algorithm   Author: rayjun   File: IteratorTraversal.java    License: MIT License 6 votes vote down vote up
/**
 * 中序遍历
 * @param root
 */
public void inOrder(TreeNode root) {
    
    Stack<TreeNode> stack = new Stack<>();
    
    if (root == null) {
        return;
    }
    TreeNode currentNode = root;

    while (currentNode != null || !stack.empty()) {
        while (currentNode != null) {
            stack.push(currentNode);
            currentNode = currentNode.left;
        }
        if (!stack.empty()) {
            currentNode = stack.pop();
            System.out.print(currentNode.val + " ");
            currentNode = currentNode.right;
        }
    }
}
 
Example #8
Source Project: tomee   Author: apache   File: References.java    License: Apache License 2.0 6 votes vote down vote up
private static void findCircuits(final Set<Circuit> circuits, final Node node, final Stack<Node> stack) {
    if (stack.contains(node)) {
        final int fromIndex = stack.indexOf(node);
        final int toIndex = stack.size();
        final ArrayList<Node> circularity = new ArrayList<>(stack.subList(fromIndex, toIndex));

        // add ending node to list so a full circuit is shown
        circularity.add(node);

        final Circuit circuit = new Circuit(circularity);

        circuits.add(circuit);

        return;
    }

    stack.push(node);

    for (final Node reference : node.initialReferences) {
        findCircuits(circuits, reference, stack);
    }

    stack.pop();
}
 
Example #9
Source Project: tomcatsrc   Author: wangyingjie   File: SystemLogHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Start capturing thread's output.
 */
public static void startCapture() {
    CaptureLog log = null;
    if (!reuse.isEmpty()) {
        try {
            log = reuse.pop();
        } catch (EmptyStackException e) {
            log = new CaptureLog();
        }
    } else {
        log = new CaptureLog();
    }
    Stack<CaptureLog> stack = logs.get();
    if (stack == null) {
        stack = new Stack<CaptureLog>();
        logs.set(stack);
    }
    stack.push(log);
}
 
Example #10
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: NamespaceMappings.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method initializes the namespace object with appropriate stacks
 * and predefines a few prefix/uri pairs which always exist.
 */
private void initNamespaces()
{


    // Define the default namespace (initially maps to "" uri)
    Stack stack;
    m_namespaces.put(EMPTYSTRING, stack = new Stack());
    stack.push(new MappingRecord(EMPTYSTRING,EMPTYSTRING,0));

    m_namespaces.put(XML_PREFIX, stack = new Stack());
    stack.push(new MappingRecord( XML_PREFIX,
        "http://www.w3.org/XML/1998/namespace",0));

    m_nodeStack.push(new MappingRecord(null,null,-1));

}
 
Example #11
Source Project: workcraft   Author: workcraft   File: CycleAlgorithm.java    License: MIT License 6 votes vote down vote up
/** function to get all strongly connected components - Tarjan algorithm **/
public List<List<Integer>> getCycles(List<Integer>[] graph) {
    mV = graph.length;
    this.graph = graph;
    low = new int[mV];
    visited = new boolean[mV];
    stack = new Stack<>();
    sccComp = new ArrayList<>();

    for (int v = 0; v < mV; v++) {
        if (!visited[v]) {
            dfs(v);
        }
    }
    return sccComp;

}
 
Example #12
Source Project: tajo   Author: apache   File: SQLBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public void visitScan(SQLBuilderContext ctx, ScanNode scan, Stack<LogicalNode> stack) {

    StringBuilder selectClause = new StringBuilder("SELECT ");
    if (scan.getTargets().size() > 0) {
      selectClause.append(generateTargetList(scan.getTargets()));
    } else {
      selectClause.append("1");
    }

    selectClause.append(" ");

    ctx.sb.append("FROM ").append(scan.getTableName()).append(" ");

    if (scan.hasAlias()) {
      ctx.sb.append("AS ").append(scan.getAlias()).append(" ");
    }

    if (scan.hasQual()) {
      ctx.sb.append("WHERE " + sqlExprGen.generate(scan.getQual()));
    }
  }
 
Example #13
Source Project: big-c   Author: yncxcw   File: Parser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given an expression and an optional comparator, build a tree of
 * InputFormats using the comparator to sort keys.
 */
static Node parse(String expr, Configuration conf) throws IOException {
  if (null == expr) {
    throw new IOException("Expression is null");
  }
  Class<? extends WritableComparator> cmpcl = conf.getClass(
    CompositeInputFormat.JOIN_COMPARATOR, null, WritableComparator.class);
  Lexer lex = new Lexer(expr);
  Stack<Token> st = new Stack<Token>();
  Token tok;
  while ((tok = lex.next()) != null) {
    if (TType.RPAREN.equals(tok.getType())) {
      st.push(reduce(st, conf));
    } else {
      st.push(tok);
    }
  }
  if (st.size() == 1 && TType.CIF.equals(st.peek().getType())) {
    Node ret = st.pop().getNode();
    if (cmpcl != null) {
      ret.setKeyComparator(cmpcl);
    }
    return ret;
  }
  throw new IOException("Missing ')'");
}
 
Example #14
Source Project: netbeans   Author: apache   File: JsFormatter.java    License: Apache License 2.0 6 votes vote down vote up
private FormatToken wrapLine(FormatContext formatContext, CodeStyle.Holder codeStyle, FormatContext.LineWrap lastWrap,
        int initialIndent, int continuationIndent, Stack<FormatContext.ContinuationBlock> continuations) {
    // we dont have to remove trailing spaces as indentation will fix it
    formatContext.insertWithOffsetDiff(lastWrap.getToken().getOffset()
            + lastWrap.getToken().getText().length(), "\n", lastWrap.getOffsetDiff()); // NOI18N
    // there is + 1 for eol
    formatContext.setCurrentLineStart(lastWrap.getToken().getOffset()
            + lastWrap.getToken().getText().length() + 1 + lastWrap.getOffsetDiff());

    FormatToken indentationEnd = FormatTokenStream.getNextNonWhite(lastWrap.getToken(), false);
    assert indentationEnd != null;

    // do the indentation
    indentLine(lastWrap.getToken(), formatContext, codeStyle, continuations,
            indentationEnd, lastWrap.getToken().getOffset() + lastWrap.getToken().getText().length() + 1,
            initialIndent, IndentUtils.indentLevelSize(formatContext.getDocument()), continuationIndent,
            true, true, Indentation.ALLOWED, lastWrap.getIndentationLevel(), lastWrap.getOffsetDiff());
    formatContext.resetTabCount();
    return indentationEnd;
}
 
Example #15
Source Project: EDDI   Author: labsai   File: ConversationCallbackTaskTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    conversationCallback = mock(IConversationCallback.class);
    when(conversationCallback.doExternalCall(any(URI.class), any(ConversationDataRequest.class), anyLong())).
            thenAnswer(invocation -> {
                ConversationDataResponse conversationDataResponse = new ConversationDataResponse();
                conversationDataResponse.setHttpCode(200);
                return conversationDataResponse;
            });
    memory = mock(IConversationMemory.class);
    IConversationMemory.IWritableConversationStep currentStep = mock(IConversationMemory.IWritableConversationStep.class);
    when(memory.getCurrentStep()).thenAnswer(invocation -> currentStep);
    when(memory.getRedoCache()).thenAnswer(invocation -> new Stack<>());
    when(memory.getAllSteps()).thenAnswer(invocation ->
            new ConversationMemory.ConversationStepStack(new LinkedList<>()));
    when(currentStep.getLatestData(eq("actions"))).thenAnswer(invocation ->
            new Data<>("actions", Collections.singletonList("action_1")));
    when(memory.getConversationProperties()).thenAnswer(invocation -> new ConversationProperties(memory));
}
 
Example #16
Source Project: java-technology-stack   Author: codeEngraver   File: Solution1.java    License: MIT License 6 votes vote down vote up
public List<Integer> preorderTraversal(TreeNode root) {

        ArrayList<Integer> res = new ArrayList<Integer>();
        if(root == null)
            return res;

        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.empty()){
            TreeNode curNode = stack.pop();
            res.add(curNode.val);

            if(curNode.right != null)
                stack.push(curNode.right);
            if(curNode.left != null)
                stack.push(curNode.left);
        }
        return res;
    }
 
Example #17
Source Project: algorithms-nutshell-2ed   Author: heineman   File: StagedDeepening.java    License: MIT License 6 votes vote down vote up
/**
 * Return stack of moves from initial state that leads to this final state
 *  
 * @param n  Final State
 */
public static Stack<IMove> computeSolution(INode n) {
	Stack<IMove> res = new Stack<IMove>();
	System.out.println(n);
	Chain ch = (Chain) n.storedData();
	if (ch == null) {
		return res;
	}
	
	// must reverse the chain
	Stack<Chain> chainStack = new Stack<Chain>();
	while (ch != null) {
		chainStack.push(ch);
		ch = ch.previous;
	}
	
	while (!chainStack.isEmpty()) {
		ch = chainStack.pop();
		for (Iterator<IMove> it = ch.moves.iterator(); it.hasNext(); ) {
			res.push(it.next());
		}
	}
	
	return res;
}
 
Example #18
Source Project: PdfBox-Android   Author: TomRoush   File: StackOperators.java    License: Apache License 2.0 5 votes vote down vote up
public void execute(ExecutionContext context)
{
    Stack<Object> stack = context.getStack();
    int n = ((Number)stack.pop()).intValue();
    if (n > 0)
    {
        int size = stack.size();
        //Need to copy to a new list to avoid ConcurrentModificationException
        List<Object> copy = new java.util.ArrayList<Object>(
                stack.subList(size - n, size));
        stack.addAll(copy);
    }
}
 
Example #19
Source Project: AndroidReview   Author: envyfan   File: AppManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 添加Activity到堆栈
 */
public void addActivity(Activity activity) {
    if (activityStack == null) {
        activityStack = new Stack<Activity>();
    }
    activityStack.add(activity);
}
 
Example #20
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: FixedHeightLayoutCache.java    License: MIT License 5 votes vote down vote up
public FixedHeightLayoutCache() {
    super();
    tempStacks = new Stack<Stack<TreePath>>();
    boundsBuffer = new Rectangle();
    treePathMapping = new Hashtable<TreePath, FHTreeStateNode>();
    info = new SearchInfo();
    setRowHeight(1);
}
 
Example #21
Source Project: oodt   Author: apache   File: AbstractCrawlLister.java    License: Apache License 2.0 5 votes vote down vote up
protected File[] crawlFiles(File dirRoot, boolean recur,
    boolean crawlForDirs) {
  if (dirRoot == null || ((!dirRoot.exists()))) {
    throw new IllegalArgumentException("dir root: [" + dirRoot
                                       + "] is null or non existant!");
  }

  List<File> fileList = new Vector<File>();

  // start crawling
  Stack<File> stack = new Stack<File>();
  stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile());
  while (!stack.isEmpty()) {
    File dir = (File) stack.pop();
    LOG.log(Level.INFO, "OFSN: Crawling " + dir);

    File[] productFiles;
    productFiles = crawlForDirs ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER);

    if(productFiles!=null) {
      Collections.addAll(fileList, productFiles);
    }
    if (recur) {
      File[] subdirs = dir.listFiles(DIR_FILTER);
      if (subdirs != null) {
        for (File subdir : subdirs) {
          stack.push(subdir);
        }
      }
    }
  }

  return fileList.toArray(new File[fileList.size()]);
}
 
Example #22
Source Project: fixflow   Author: fixteam   File: Context.java    License: Apache License 2.0 5 votes vote down vote up
public static void removeAbstractScriptLanguageMgmt() {

		Stack<AbstractScriptLanguageMgmt> abstractScriptLanguageMgmts = getStack(abstractScriptLanguageMgmtThreadLocal);

		for (int i = 0; i < abstractScriptLanguageMgmts.size(); i++) {
			abstractScriptLanguageMgmts.get(i).close();
		}
		abstractScriptLanguageMgmts.clear();
	}
 
Example #23
Source Project: sakai   Author: sakaiproject   File: BaseDbDoubleStorage.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Add a new Resource with this id.
 * 
 * @param container
 *        The container for this resource.
 * @param id
 *        The id.
 * @param others
 *        Other fields for the newResource call
 * @return The locked Resource object with this id, or null if the id is in use.
 */
public Edit putResource(Entity container, String id, Object[] others)
{
	// create one with just the id, and perhaps some other fields, too
	Entity entry = m_user.newResource(container, id, others);

	// form the XML and SQL for the insert
	Document doc = StorageUtils.createDocument();
	entry.toXml(doc, new Stack());
	String xml = StorageUtils.writeDocumentToString(doc);

	String statement = doubleStorageSql.getInsertSql3(m_resourceTableName, insertFields(m_containerTableIdField, m_resourceTableIdField,
			m_resourceTableOtherFields, "XML"), valuesParams(m_resourceTableOtherFields));
	Object[] flds = m_user.storageFields(entry);

	if (flds == null) flds = new Object[0];
	Object[] fields = new Object[flds.length + 3];
	System.arraycopy(flds, 0, fields, 2, flds.length);
	fields[0] = container.getReference();
	fields[1] = entry.getId();
	fields[fields.length - 1] = xml;

	// process the insert
	boolean ok = m_sql.dbWrite(statement, fields);

	// if this failed, assume a key conflict (i.e. id in use)
	if (!ok) return null;

	// now get a lock on the record for edit
	Edit edit = editResource(container, id);
	if (edit == null)
	{
		log.warn("putResource(): didn't get a lock!");
		return null;
	}

	return edit;
}
 
Example #24
Source Project: FoxBPM   Author: FoxBPM   File: Context.java    License: Apache License 2.0 5 votes vote down vote up
public static AbstractScriptLanguageMgmt getAbstractScriptLanguageMgmt() {
	Stack<AbstractScriptLanguageMgmt> stack = getStack(abstractScriptLanguageMgmtThreadLocal);
	if (stack.isEmpty()) {
		return null;
	}
	return stack.peek();
}
 
Example #25
Source Project: pcgen   Author: PCGen   File: IfCommandTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void runIf(final Stack stack, final PostfixMathCommandI pCommand)
{
    try
    {
        pCommand.run(stack);
    }
    catch (ParseException ignored)
    {
    }
}
 
Example #26
Source Project: Concurnas   Author: Concurnas   File: OnCompileFrame.java    License: MIT License 5 votes vote down vote up
public Stack<Value> copyStack(){
	Stack<Value> ret = new Stack<Value>();
	//soft copy is fine
	ret.addAll(stack);
	
	return ret;
}
 
Example #27
Source Project: netbeans   Author: apache   File: LibraryDeclarationParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a parser instance.
 * @param handler handler interface implementation (never <code>null</code>
 * It is recommended that it could be able to resolve at least the [email protected] parslet convertors implementation (never <code>null</code>
 *
 */
public LibraryDeclarationParser(final LibraryDeclarationHandler handler, final LibraryDeclarationConvertor parslet) {
    this.parslet = parslet;
    this.handler = handler;
    buffer = new StringBuffer(111);
    context = new Stack<Object[]>();
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: Digester.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the currently mapped namespace URI for the specified prefix,
 * if any; otherwise return <code>null</code>.  These mappings come and
 * go dynamically as the document is parsed.
 *
 * @param prefix Prefix to look up
 */
public String findNamespaceURI(String prefix) {
    
    Stack<String> nsStack = namespaces.get(prefix);
    if (nsStack == null) {
        return null;
    }
    try {
        return (nsStack.peek());
    } catch (EmptyStackException e) {
        return null;
    }

}
 
Example #29
Source Project: Android-RTEditor   Author: 1gravity   File: RTOperationManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Re-do the last undone operation for a specific rich text editor
 *
 * @param editor Re-do an operation for this rich text editor
 */
synchronized void redo(RTEditText editor) {
    Stack<Operation> redoStack = getRedoStack(editor);
    if (!redoStack.empty()) {
        Stack<Operation> undoStack = getUndoStack(editor);
        Operation op = redoStack.pop();
        push(op, undoStack);
        op.redo(editor);
        while (!redoStack.empty() && op.canMerge(redoStack.peek())) {
            op = redoStack.pop();
            push(op, undoStack);
            op.redo(editor);
        }
    }
}
 
Example #30
Source Project: onedev   Author: theonedev   File: DataMigrator.java    License: MIT License 5 votes vote down vote up
private void migrate2(File dataDir, Stack<Integer> versions) {
	for (File file: dataDir.listFiles()) {
		if (file.getName().startsWith("Depots.xml")) {
			VersionedXmlDoc dom = VersionedXmlDoc.fromFile(file);
			for (Element element: dom.getRootElement().elements()) {
				Element gateKeeperElement = element.element("gateKeeper");
				gateKeeperElement.detach();
				element.addElement("gateKeepers");
			}
			dom.writeToFile(file, false);
		}
	}	
}