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 File: StagedDeepening.java    From algorithms-nutshell-2ed with 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 #2
Source File: NamespaceMappings.java    From openjdk-jdk9 with 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
Source File: SecondMinNodeInBinaryTree.java    From Algorithms-and-Data-Structures-in-Java with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 File: BallTree.java    From rapidminer-studio with 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 #5
Source File: NamespaceMappings.java    From openjdk-jdk8u-backup with 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 #6
Source File: ScopeTestUtil.java    From toothpick with 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 #7
Source File: Node.java    From coderadar with 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 #8
Source File: IteratorTraversal.java    From awesome-algorithm with 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 #9
Source File: SystemLogHandler.java    From tomcatsrc with 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 File: CycleAlgorithm.java    From workcraft with 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 #11
Source File: SQLBuilder.java    From tajo with 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 #12
Source File: Parser.java    From big-c with 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 #13
Source File: JsFormatter.java    From netbeans with 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 #14
Source File: NamespaceMappings.java    From openjdk-jdk8u with 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 #15
Source File: ConversationCallbackTaskTest.java    From EDDI with 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 File: Solution1.java    From java-technology-stack with 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 File: References.java    From tomee with 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 #18
Source File: DependencyTree.java    From gAnswer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public DependencyTree (Sentence sentence, CoreNLP coreNLPparser) {
	SemanticGraph dependencies = coreNLPparser.getBasicDependencies(sentence.plainText);
	this.dependencies = dependencies;
	
	Stack<IndexedWord> stack = new Stack<IndexedWord>();
	IndexedWord iwRoot = dependencies.getFirstRoot();
	
	HashMap<IndexedWord, DependencyTreeNode> map = new HashMap<IndexedWord, DependencyTreeNode>();
	nodesList = new ArrayList<DependencyTreeNode>();

	stack.push(iwRoot);
	root = this.setRoot(sentence.getWordByIndex(iwRoot.index()));
	map.put(iwRoot, root);

	while (!stack.empty())
	{
		IndexedWord curIWNode = stack.pop();
		DependencyTreeNode curDTNode = map.get(curIWNode);
		
		for (IndexedWord iwChild : dependencies.getChildList(curIWNode)) {
			Word w = sentence.getWordByIndex(iwChild.index());
			DependencyTreeNode newDTNode = this.insert(
					curDTNode, 
					w, 
					dependencies.reln(curIWNode, iwChild).getShortName());
			map.put(iwChild, newDTNode);
			stack.push(iwChild);
		}
		
		curDTNode.sortChildrenList();
		nodesList.add(curDTNode);
	}
}
 
Example #19
Source File: Context.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
public static ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
	Stack<ProcessEngineConfigurationImpl> stack = getStack(processEngineConfigurationStackThreadLocal);
	if (stack.isEmpty()) {
		return null;
	}
	return stack.peek();
}
 
Example #20
Source File: LogicalPlanVerifier.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
@Override
public LogicalNode visitGroupBy(VerificationState state, LogicalPlan plan, LogicalPlan.QueryBlock block,
                                GroupbyNode node, Stack<LogicalNode> stack) throws PlanningException {
  super.visitGroupBy(state, plan, block, node, stack);

  verifyProjectableOutputSchema(node);
  return node;
}
 
Example #21
Source File: Context.java    From fixflow with 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 #22
Source File: SwipeLayout.java    From FragmentRigger with MIT License 5 votes vote down vote up
@Nullable
private Activity getPreActivity() {
    if (mPuppetHost instanceof Activity) {
        Stack<Activity> stack = SwipeActivityManager.getInstance().getActivityStack();
        int index = stack.indexOf(mPuppetHost);
        if (index <= 0) {
            return null;
        }
        return stack.get(index - 1);
    }
    return null;
}
 
Example #23
Source File: EdgeWeightedDirectedCycle.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private void dfs(EdgeWeightedDigraph G, int v)
{
	onStack[v] = true;
	marked[v] = true;
	for (DirectedEdge e : G.adj(v))
	{
		int w = e.to();
		
		// short circuit if directed cycle found
		if (cycle != null)
			return;
		
		// found new vertex, so recur
		else if (!marked[w])
		{
			edgeTo[w] = e;
			dfs(G, w);
		}
		
		// trace back directed cycle
		else if (onStack[w])
		{
			cycle = new Stack<DirectedEdge>();
			while (e.from() != w)
			{
				cycle.push(e);
				e = edgeTo[e.from()];
			}
			cycle.push(e);
		}
	}
	
	onStack[v] = false;
}
 
Example #24
Source File: BaseDbDoubleStorage.java    From sakai with 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 #25
Source File: Context.java    From FoxBPM with 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 #26
Source File: StreamScaler.java    From amazon-kinesis-scaling-utils with Apache License 2.0 5 votes vote down vote up
private Stack<ShardHashInfo> getOpenShardStack(String streamName) throws Exception {
	// populate the stack with the current set of shards
	Stack<ShardHashInfo> shardStack = new Stack<>();
	List<ShardHashInfo> shards = new ArrayList<>(
			StreamScalingUtils.getOpenShards(this.kinesisClient, streamName, SortOrder.DESCENDING, null).values());
	for (ShardHashInfo s : shards) {
		shardStack.push(s);
	}

	return shardStack;
}
 
Example #27
Source File: LogicalPlanVerifier.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public LogicalNode visitTableSubQuery(Context context, LogicalPlan plan, LogicalPlan.QueryBlock block,
                                 TableSubQueryNode node, Stack<LogicalNode> stack) throws TajoException {
  super.visitTableSubQuery(context, plan, block, node, stack);
  if (node.hasTargets()) {
    for (Target target : node.getTargets()) {
      ExprsVerifier.verify(context.state, node, target.getEvalTree());
    }
  }

  verifyProjectableOutputSchema(context, node);
  return node;
}
 
Example #28
Source File: FixedHeightLayoutCache.java    From Java8CN with Apache License 2.0 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 #29
Source File: TrackableCollection.java    From bindroid with MIT License 5 votes vote down vote up
/**
 * Constructs a new ObservableCollection backed by the given {@link List} implementation.
 * 
 * @param backingStore
 *          The list implementation for the ObservableCollection.
 */
public TrackableCollection(List<T> backingStore) {
  this.backingStore = backingStore;
  this.ids = new ArrayList<Long>();
  this.returnedIds = new Stack<Long>();
  for (int x = 0; x < backingStore.size(); x++) {
    this.ids.add(this.getNewId());
  }
}
 
Example #30
Source File: StackOperators.java    From PdfBox-Android with 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);
    }
}