下面列出了怎么用java.util.Stack的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
/**
* 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;
}
/**
* 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;
}
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;
}
/**
* 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);
}
}
}
/**
* 中序遍历
* @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;
}
}
}
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();
}
/**
* 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);
}
/**
* 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));
}
/** 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;
}
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()));
}
}
/**
* 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 ')'");
}
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;
}
@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));
}
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;
}
/**
* 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;
}
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);
}
}
/**
* 添加Activity到堆栈
*/
public void addActivity(Activity activity) {
if (activityStack == null) {
activityStack = new Stack<Activity>();
}
activityStack.add(activity);
}
public FixedHeightLayoutCache() {
super();
tempStacks = new Stack<Stack<TreePath>>();
boundsBuffer = new Rectangle();
treePathMapping = new Hashtable<TreePath, FHTreeStateNode>();
info = new SearchInfo();
setRowHeight(1);
}
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()]);
}
public static void removeAbstractScriptLanguageMgmt() {
Stack<AbstractScriptLanguageMgmt> abstractScriptLanguageMgmts = getStack(abstractScriptLanguageMgmtThreadLocal);
for (int i = 0; i < abstractScriptLanguageMgmts.size(); i++) {
abstractScriptLanguageMgmts.get(i).close();
}
abstractScriptLanguageMgmts.clear();
}
/**
* 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;
}
public static AbstractScriptLanguageMgmt getAbstractScriptLanguageMgmt() {
Stack<AbstractScriptLanguageMgmt> stack = getStack(abstractScriptLanguageMgmtThreadLocal);
if (stack.isEmpty()) {
return null;
}
return stack.peek();
}
private static void runIf(final Stack stack, final PostfixMathCommandI pCommand)
{
try
{
pCommand.run(stack);
}
catch (ParseException ignored)
{
}
}
public Stack<Value> copyStack(){
Stack<Value> ret = new Stack<Value>();
//soft copy is fine
ret.addAll(stack);
return ret;
}
/**
* 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[]>();
}
/**
* 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;
}
}
/**
* 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);
}
}
}
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);
}
}
}