类java.util.Stack源码实例Demo

下面列出了怎么用java.util.Stack的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: rapidminer-studio   文件: BallTree.java
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);
}
 
源代码2 项目: openjdk-jdk9   文件: NamespaceMappings.java
/**
 * 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;
}
 
/**
 * 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;
}
 
源代码4 项目: openjdk-jdk8u-backup   文件: NamespaceMappings.java
/**
 * 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;
}
 
源代码5 项目: toothpick   文件: ScopeTestUtil.java
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;
}
 
源代码6 项目: coderadar   文件: Node.java
/**
 * 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);
    }
  }
}
 
源代码7 项目: awesome-algorithm   文件: IteratorTraversal.java
/**
 * 中序遍历
 * @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;
        }
    }
}
 
源代码8 项目: tomee   文件: References.java
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();
}
 
源代码9 项目: tomcatsrc   文件: SystemLogHandler.java
/**
 * 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);
}
 
源代码10 项目: openjdk-jdk8u   文件: NamespaceMappings.java
/**
 * 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));

}
 
源代码11 项目: workcraft   文件: CycleAlgorithm.java
/** 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;

}
 
源代码12 项目: tajo   文件: SQLBuilder.java
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()));
    }
  }
 
源代码13 项目: big-c   文件: Parser.java
/**
 * 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 ')'");
}
 
源代码14 项目: netbeans   文件: JsFormatter.java
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;
}
 
源代码15 项目: EDDI   文件: ConversationCallbackTaskTest.java
@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));
}
 
源代码16 项目: java-technology-stack   文件: Solution1.java
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;
    }
 
源代码17 项目: algorithms-nutshell-2ed   文件: StagedDeepening.java
/**
 * 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;
}
 
源代码18 项目: PdfBox-Android   文件: StackOperators.java
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);
    }
}
 
源代码19 项目: AndroidReview   文件: AppManager.java
/**
 * 添加Activity到堆栈
 */
public void addActivity(Activity activity) {
    if (activityStack == null) {
        activityStack = new Stack<Activity>();
    }
    activityStack.add(activity);
}
 
源代码20 项目: JDKSourceCode1.8   文件: FixedHeightLayoutCache.java
public FixedHeightLayoutCache() {
    super();
    tempStacks = new Stack<Stack<TreePath>>();
    boundsBuffer = new Rectangle();
    treePathMapping = new Hashtable<TreePath, FHTreeStateNode>();
    info = new SearchInfo();
    setRowHeight(1);
}
 
源代码21 项目: oodt   文件: AbstractCrawlLister.java
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()]);
}
 
源代码22 项目: fixflow   文件: Context.java
public static void removeAbstractScriptLanguageMgmt() {

		Stack<AbstractScriptLanguageMgmt> abstractScriptLanguageMgmts = getStack(abstractScriptLanguageMgmtThreadLocal);

		for (int i = 0; i < abstractScriptLanguageMgmts.size(); i++) {
			abstractScriptLanguageMgmts.get(i).close();
		}
		abstractScriptLanguageMgmts.clear();
	}
 
源代码23 项目: sakai   文件: BaseDbDoubleStorage.java
/**
 * 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;
}
 
源代码24 项目: FoxBPM   文件: Context.java
public static AbstractScriptLanguageMgmt getAbstractScriptLanguageMgmt() {
	Stack<AbstractScriptLanguageMgmt> stack = getStack(abstractScriptLanguageMgmtThreadLocal);
	if (stack.isEmpty()) {
		return null;
	}
	return stack.peek();
}
 
源代码25 项目: pcgen   文件: IfCommandTest.java
private static void runIf(final Stack stack, final PostfixMathCommandI pCommand)
{
    try
    {
        pCommand.run(stack);
    }
    catch (ParseException ignored)
    {
    }
}
 
源代码26 项目: Concurnas   文件: OnCompileFrame.java
public Stack<Value> copyStack(){
	Stack<Value> ret = new Stack<Value>();
	//soft copy is fine
	ret.addAll(stack);
	
	return ret;
}
 
源代码27 项目: netbeans   文件: LibraryDeclarationParser.java
/**
 * 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[]>();
}
 
源代码28 项目: lams   文件: Digester.java
/**
 * 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;
    }

}
 
源代码29 项目: Android-RTEditor   文件: RTOperationManager.java
/**
 * 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);
        }
    }
}
 
源代码30 项目: onedev   文件: DataMigrator.java
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);
		}
	}	
}
 
 类所在包
 同包方法