下面列出了java.util.Stack#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check pairs.
* @param test
* the test
* @return true, if successful
*/
private boolean checkPairs(String test) {
String[] parts = test.trim().split("<"); //$NON-NLS-1$
Stack<String> stack = new Stack<String>();
for (int i = 0; i < parts.length; i++) {
if (parts[i].length() > 0) {
String[] subparts = parts[i].split("[\\s]|[>]"); //$NON-NLS-1$
if (subparts[0].startsWith("/")) { //$NON-NLS-1$
if (stack.size() == 0) {
return false;
} else {
String last = stack.pop();
if (!last.equals(subparts[0].substring(1))) {
return false;
}
}
} else {
stack.push(subparts[0]);
}
}
}
if (stack.size() == 0) {
return true;
}
return false;
}
public String[] bases (String x){
try {
// default to using the current ORB version in case the
// vhandler is not set
if (vhandler == null) {
vhandler = ValueHandlerImpl.getInstance(false);
}
Stack repIds = new Stack();
Class parent = ObjectStreamClass.lookup(vhandler.getClassFromType(x)).forClass().getSuperclass();
while (!parent.equals(java.lang.Object.class)) {
repIds.push(vhandler.createForAnyType(parent));
parent = parent.getSuperclass();
}
String result[] = new String[repIds.size()];
for (int i = result.length - 1; i >= 0; i++)
result[i] = (String)repIds.pop();
return result;
} catch (Throwable t) {
throw wrapper.missingLocalValueImpl( CompletionStatus.COMPLETED_MAYBE, t );
}
}
/**
* There're 3 special RelNode in parents stack, OLAPProjectRel, OLAPToEnumerableConverter
* and OLAPUnionRel. OLAPProjectRel will helps collect required columns but the other two
* don't. Go through the parent RelNodes from bottom to top, and the first-met special
* RelNode determines the behavior.
* * OLAPProjectRel -> skip column collection
* * OLAPToEnumerableConverter and OLAPUnionRel -> require column collection
*/
private boolean needCollectionColumns(OLAPImplementor implementor) {
Stack<RelNode> allParents = implementor.getParentNodeStack();
int index = allParents.size() - 1;
while (index >= 0) {
RelNode parent = allParents.get(index);
if (parent instanceof OLAPProjectRel) {
return false;
}
if (parent instanceof OLAPToEnumerableConverter || parent instanceof OLAPUnionRel) {
return true;
}
OLAPRel olapParent = (OLAPRel) allParents.get(index);
if (olapParent.getContext() != null && olapParent.getContext() != this.context) {
// if the whole context has not projection, let table scan take care of itself
break;
}
index--;
}
return true;
}
public static BinaryTree<Integer> LCA(BinaryTree<Integer> tree, BinaryTree<Integer> node0, BinaryTree<Integer> node1) {
Stack<BinaryTree<Integer>> zero = dfs(tree, node0, new Stack<>());
Stack<BinaryTree<Integer>> one = dfs(tree, node1, new Stack<>());
//ITERATE BOTH STACKS
while (!zero.isEmpty() && !one.isEmpty()) {
if (zero.size() > one.size()) {
//IF STACK ZERO IS BIGGER GET TO SAME LEVEL AS ONE
zero.pop();
} else if (zero.size() < one.size()) {
//IF STACK ONE IS BIGGER GET TO SAME LEVEL AS ZERO
one.pop();
} else {
//IF STACKS ARE EQUAL SEE IF THEY HAVE THE SAME NODE
if (zero.peek().equals(one.peek()))
return zero.pop();
zero.pop();
one.pop();
}
}
return new BinaryTree<>(0);
}
private boolean checkUnDeployLogOrder(LogViewerClient logViewerClient)
throws RemoteException {
LogEvent[] systemLogs;
systemLogs = logViewerClient.getAllRemoteSystemLogs();
//Create a stack to store the intended logs in order
Stack<String> logStack = new Stack<>();
logStack.push("Inbound Endpoint named 'inbound-endpoint' has been undeployed");
logStack.push("Sequence named 'test-sequence' has been undeployed");
//Check whether the logs are in the stack's order
if (systemLogs != null) {
for (LogEvent logEvent : systemLogs) {
if (logEvent == null) {
continue;
}
if (logStack.size() != 0 && logEvent.getMessage().contains(logStack.peek())){
logStack.pop();
}
}
}
return logStack.isEmpty();
}
@Override
public void setLabelBeforeAction(Label endLabel) {
Stack<Pair<Label, Block>> onEntry = this.getLinesToVisitOnEntry();
//they are stored in reverse order
for(int n=onEntry.size()-1; n >= 0; n--){
Pair<Label, Block> level = onEntry.get(n);
if(level.getA()!=null){
onEntry.set(n, new Pair<Label, Block>(endLabel, level.getB()));//overrite the label
return;
}
}
//nothing extra to insert so...
setLabelToVisitJustBeforeReturnOpCode(endLabel);
}
/**
* Calculates the length of the the sub-path in a transition path, that is used only by a given string.
* @param str a String corresponding to a transition path from sourceNode
* @return an int denoting the size of the sub-path in the transition path
* corresponding to {@code str} that is only used by {@code str}
*/
private int calculateSoleTransitionPathLength(String str)
{
Stack<MDAGNode> transitionPathNodeStack = sourceNode.getTransitionPathNodes(str);
transitionPathNodeStack.pop(); //The MDAGNode at the top of the stack is not needed
//(we are processing the outgoing transitions of nodes inside str's transition path,
//the outgoing transitions of the MDAGNode at the top of the stack are outside this path)
transitionPathNodeStack.trimToSize();
//Process each node in transitionPathNodeStack, using each to determine whether the
//transition path corresponding to str is only used by str. This is true if and only if
//each node in the transition path has a single outgoing transition and is not an accept state.
while(!transitionPathNodeStack.isEmpty())
{
MDAGNode currentNode = transitionPathNodeStack.peek();
if(currentNode.getOutgoingTransitions().size() <= 1 && !currentNode.isAcceptNode())
transitionPathNodeStack.pop();
else
break;
}
/////
return (transitionPathNodeStack.capacity() - transitionPathNodeStack.size());
}
/**
* Given an expression and an optional comparator, build a tree of
* InputFormats using the comparator to sort keys.
*/
static Node parse(String expr, JobConf job) throws IOException {
if (null == expr) {
throw new IOException("Expression is null");
}
Class<? extends WritableComparator> cmpcl =
job.getClass("mapred.join.keycomparator", 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, job));
} 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 ')'");
}
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int asteroid : asteroids) {
collision:
{
while (!stack.isEmpty() && asteroid < 0 && stack.peek() > 0) {
if (stack.peek() + asteroid < 0) {
stack.pop();
continue;
} else if (stack.peek() + asteroid == 0) {
stack.pop();
}
break collision;
}
stack.push(asteroid);
}
}
int size = stack.size();
int[] res = new int[size];
int index = size - 1;
while (!stack.isEmpty()) {
res[index] = stack.pop();
index--;
}
return res;
}
private void ensureUniqueCanonicalStack(int jumpsrc, int jumpdest, Stack<Variable> stack) {
// check if the current stack is going to be used as a canonical stack
if (!canonicalStackForBranchJoinJumpdest.containsKey(jumpdest)) {
// if so, check for duplicate variables in the stack, which may cause merge conflicts
if (stack.size() != stack.stream().distinct().count()) {
log.println("undup canonical stack @" + toHex(jumpdest));
// map duplicate variables to new ones
if (jumpsrc != -1 && variableReassignments.containsKey(jumpsrc) || jumpsrc == -1 && variableReassignmentsInline.containsKey(jumpsrc)) {
throw new IllegalStateException("reassignment does already exist");
}
Map<Variable, Variable> reassignments = new HashMap<>();
Set<Variable> processedVars = new HashSet<>();
for (int i = 0; i < stack.size(); ++i) {
Variable var = stack.get(i);
if (processedVars.contains(var)) {
// duplicate variable, create new one with reassigment
Variable undupVar = new Variable();
stack.set(i, undupVar);
reassignments.put(undupVar, var);
log.println(" " + undupVar + " <- " + var);
}
else {
processedVars.add(var);
}
}
if (jumpsrc == -1) {
variableReassignmentsInline.put(jumpdest, reassignments);
}
else {
variableReassignments.put(jumpsrc, reassignments);
}
}
}
}
public static void main (String [] args) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s=br.readLine())!=null) {
StringTokenizer st=new StringTokenizer(s);
Stack<Doll> stk=new Stack<>();
int dollCount=0;
while (st.hasMoreTokens()) {
int n=Integer.parseInt(st.nextToken());
dollCount++;
if (n<0) {
Doll d=new Doll(-n);
if (stk.empty()) stk.add(d);
else if (stk.peek().emptySpace>d.size) {
stk.peek().emptySpace-=d.size;
stk.add(d);
} else break;
} else {
if (!stk.isEmpty() && stk.peek().size==n) stk.pop();
else break;
}
}
if (stk.size()==0 && dollCount%2==0) System.out.println(":-) Matrioshka!");
else System.out.println(":-( Try again.");
}
}
/**
* Construct a QName from a string, resolving the prefix
* using the given namespace stack. The default namespace is
* not resolved.
*
* @param qname Qualified name to resolve
* @param namespaces Namespace stack to use to resolve namespace
* @param validate If true the new QName will be validated and an IllegalArgumentException will
* be thrown if it is invalid.
*/
public QName(String qname, Stack<NameSpace> namespaces, boolean validate)
{
String namespace = null;
String prefix = null;
int indexOfNSSep = qname.indexOf(':');
if (indexOfNSSep > 0)
{
prefix = qname.substring(0, indexOfNSSep);
if (prefix.equals("xml"))
{
namespace = S_XMLNAMESPACEURI;
}
// Do we want this?
else if (prefix.equals("xmlns"))
{
return;
}
else
{
int depth = namespaces.size();
for (int i = depth - 1; i >= 0; i--)
{
NameSpace ns = namespaces.get(i);
while (null != ns)
{
if ((null != ns.m_prefix) && prefix.equals(ns.m_prefix))
{
namespace = ns.m_uri;
i = -1;
break;
}
ns = ns.m_next;
}
}
}
if (null == namespace)
{
throw new RuntimeException(
XMLMessages.createXMLMessage(
XMLErrorResources.ER_PREFIX_MUST_RESOLVE,
new Object[]{ prefix })); //"Prefix must resolve to a namespace: "+prefix);
}
}
_localName = (indexOfNSSep < 0)
? qname : qname.substring(indexOfNSSep + 1);
if (validate)
{
if ((_localName == null) || (!XML11Char.isXML11ValidNCName(_localName)))
{
throw new IllegalArgumentException(XMLMessages.createXMLMessage(
XMLErrorResources.ER_ARG_LOCALNAME_INVALID,null )); //"Argument 'localName' not a valid NCName");
}
}
_namespaceURI = namespace;
_prefix = prefix;
m_hashCode = toString().hashCode();
}
/**
* Returns the TreeStateNode identified by path. This mirrors
* the behavior of getNodeForPath, but tries to take advantage of
* path if it is an instance of AbstractTreePath.
*/
private TreeStateNode getNodeForPath(TreePath path,
boolean onlyIfVisible,
boolean shouldCreate) {
if(path != null) {
TreeStateNode node;
node = getMapping(path);
if(node != null) {
if(onlyIfVisible && !node.isVisible())
return null;
return node;
}
// Check all the parent paths, until a match is found.
Stack<TreePath> paths;
if(tempStacks.size() == 0) {
paths = new Stack<TreePath>();
}
else {
paths = tempStacks.pop();
}
try {
paths.push(path);
path = path.getParentPath();
node = null;
while(path != null) {
node = getMapping(path);
if(node != null) {
// Found a match, create entries for all paths in
// paths.
while(node != null && paths.size() > 0) {
path = paths.pop();
node.getLoadedChildren(shouldCreate);
int childIndex = treeModel.
getIndexOfChild(node.getUserObject(),
path.getLastPathComponent());
if(childIndex == -1 ||
childIndex >= node.getChildCount() ||
(onlyIfVisible && !node.isVisible())) {
node = null;
}
else
node = (TreeStateNode)node.getChildAt
(childIndex);
}
return node;
}
paths.push(path);
path = path.getParentPath();
}
}
finally {
paths.removeAllElements();
tempStacks.push(paths);
}
// If we get here it means they share a different root!
// We could throw an exception...
}
return null;
}
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
if (!(file instanceof HaxeFile)) return null;
final List<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>();
final ProblemReporter reporter = new ProblemReporter() {
@Override
public void reportProblem(ASTNode node, String message) {
result.add( manager.createProblemDescriptor( node.getPsi(),
message,
(LocalQuickFix)null,
ProblemHighlightType.ERROR,
isOnTheFly));
}
};
FileASTNode node1 = file.getNode();
LeafElement firstLeaf = TreeUtil.findFirstLeaf(node1);
Stack<List<ASTNode>> levels = new Stack<List<ASTNode>>();
List<ASTNode> nodes = new ArrayList<ASTNode>();
// Push the root node, just in case there is no #if to start it off.
levels.push(nodes);
ASTNode leaf = firstLeaf;
while (leaf != null) {
IElementType leafElementType = leaf.getElementType();
if (leafElementType.equals(HaxeTokenTypes.PPIF)) {
nodes = new ArrayList<ASTNode>();
levels.push(nodes);
nodes.add(leaf);
}
else if (leafElementType.equals(HaxeTokenTypes.PPEND)) {
nodes.add(leaf);
// Leave the base level in place, even if there are extra ends.
if (levels.size() > 1) {
validateLevel(nodes, reporter);
levels.pop();
nodes = levels.peek();
}
}
else if (leafElementType.equals(HaxeTokenTypes.PPELSEIF)) {
nodes.add(leaf);
}
else if (leafElementType.equals(HaxeTokenTypes.PPELSE)) {
nodes.add(leaf);
}
leaf = TreeUtil.nextLeaf(leaf);
}
// Any levels that are still left need to be validated.
for (List<ASTNode> level : levels) {
validateLevel(level, reporter);
}
return ArrayUtil.toObjectArray(result, ProblemDescriptor.class);
}
/**
* Construct a QName from a string, resolving the prefix
* using the given namespace stack. The default namespace is
* not resolved.
*
* @param qname Qualified name to resolve
* @param namespaces Namespace stack to use to resolve namespace
* @param validate If true the new QName will be validated and an IllegalArgumentException will
* be thrown if it is invalid.
*/
public QName(String qname, Stack namespaces, boolean validate)
{
String namespace = null;
String prefix = null;
int indexOfNSSep = qname.indexOf(':');
if (indexOfNSSep > 0)
{
prefix = qname.substring(0, indexOfNSSep);
if (prefix.equals("xml"))
{
namespace = S_XMLNAMESPACEURI;
}
// Do we want this?
else if (prefix.equals("xmlns"))
{
return;
}
else
{
int depth = namespaces.size();
for (int i = depth - 1; i >= 0; i--)
{
NameSpace ns = (NameSpace) namespaces.elementAt(i);
while (null != ns)
{
if ((null != ns.m_prefix) && prefix.equals(ns.m_prefix))
{
namespace = ns.m_uri;
i = -1;
break;
}
ns = ns.m_next;
}
}
}
if (null == namespace)
{
throw new RuntimeException(
XMLMessages.createXMLMessage(
XMLErrorResources.ER_PREFIX_MUST_RESOLVE,
new Object[]{ prefix })); //"Prefix must resolve to a namespace: "+prefix);
}
}
_localName = (indexOfNSSep < 0)
? qname : qname.substring(indexOfNSSep + 1);
if (validate)
{
if ((_localName == null) || (!XML11Char.isXML11ValidNCName(_localName)))
{
throw new IllegalArgumentException(XMLMessages.createXMLMessage(
XMLErrorResources.ER_ARG_LOCALNAME_INVALID,null )); //"Argument 'localName' not a valid NCName");
}
}
_namespaceURI = namespace;
_prefix = prefix;
m_hashCode = toString().hashCode();
}
/**
* Messages getTreeNodeForPage(path, onlyIfVisible, shouldCreate,
* path.length) as long as path is non-null and the length is {@literal >} 0.
* Otherwise returns null.
*/
private FHTreeStateNode getNodeForPath(TreePath path,
boolean onlyIfVisible,
boolean shouldCreate) {
if(path != null) {
FHTreeStateNode node;
node = getMapping(path);
if(node != null) {
if(onlyIfVisible && !node.isVisible())
return null;
return node;
}
if(onlyIfVisible)
return null;
// Check all the parent paths, until a match is found.
Stack<TreePath> paths;
if(tempStacks.size() == 0) {
paths = new Stack<TreePath>();
}
else {
paths = tempStacks.pop();
}
try {
paths.push(path);
path = path.getParentPath();
node = null;
while(path != null) {
node = getMapping(path);
if(node != null) {
// Found a match, create entries for all paths in
// paths.
while(node != null && paths.size() > 0) {
path = paths.pop();
node = node.createChildFor(path.
getLastPathComponent());
}
return node;
}
paths.push(path);
path = path.getParentPath();
}
}
finally {
paths.removeAllElements();
tempStacks.push(paths);
}
// If we get here it means they share a different root!
return null;
}
return null;
}
/**
* Returns the TreeStateNode identified by path. This mirrors
* the behavior of getNodeForPath, but tries to take advantage of
* path if it is an instance of AbstractTreePath.
*/
private TreeStateNode getNodeForPath(TreePath path,
boolean onlyIfVisible,
boolean shouldCreate) {
if(path != null) {
TreeStateNode node;
node = getMapping(path);
if(node != null) {
if(onlyIfVisible && !node.isVisible())
return null;
return node;
}
// Check all the parent paths, until a match is found.
Stack<TreePath> paths;
if(tempStacks.size() == 0) {
paths = new Stack<TreePath>();
}
else {
paths = tempStacks.pop();
}
try {
paths.push(path);
path = path.getParentPath();
node = null;
while(path != null) {
node = getMapping(path);
if(node != null) {
// Found a match, create entries for all paths in
// paths.
while(node != null && paths.size() > 0) {
path = paths.pop();
node.getLoadedChildren(shouldCreate);
int childIndex = treeModel.
getIndexOfChild(node.getUserObject(),
path.getLastPathComponent());
if(childIndex == -1 ||
childIndex >= node.getChildCount() ||
(onlyIfVisible && !node.isVisible())) {
node = null;
}
else
node = (TreeStateNode)node.getChildAt
(childIndex);
}
return node;
}
paths.push(path);
path = path.getParentPath();
}
}
finally {
paths.removeAllElements();
tempStacks.push(paths);
}
// If we get here it means they share a different root!
// We could throw an exception...
}
return null;
}
/** Handle an operand */
private static Operand handleOperand( String sourceField, BSONObject exp ) {
Operand current = null;
Object value = null;
for ( String field : exp.keySet() ) {
if ( field.startsWith( "$" ) ) {
if ( "$gt".equals( field ) ) {
value = exp.get( field );
GreaterThan gt = new GreaterThan();
gt.setProperty( sourceField );
gt.setLiteral( value );
current = gt;
}
else if ( "$gte".equals( field ) ) {
value = exp.get( field );
GreaterThanEqual gte = new GreaterThanEqual();
gte.setProperty( sourceField );
gte.setLiteral( exp.get( field ) );
current = gte;
// http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%3C%2C%3C%3D%2C%3E%2C%3E%3D
// greater than equals
// { "field" : { $gte: value } }
}
else if ( "$lt".equals( field ) ) {
value = exp.get( field );
LessThan lt = new LessThan();
lt.setProperty( sourceField );
lt.setLiteral( value );
current = lt;
}
else if ( "$lte".equals( field ) ) {
value = exp.get( field );
LessThanEqual lte = new LessThanEqual();
lte.setProperty( sourceField );
lte.setLiteral( value );
current = lte;
}
else if ( "$in".equals( field ) ) {
value = exp.get( field );
BasicBSONList values = ( BasicBSONList ) value;
int size = values.size();
Stack<Operand> expressions = new Stack<Operand>();
for (Object value1 : values) {
Equal equal = new Equal();
equal.setProperty(sourceField);
equal.setLiteral(value1);
expressions.push(equal);
}
// we need to build a tree of expressions
while ( expressions.size() > 1 ) {
OrOperand or = new OrOperand();
or.addChild( expressions.pop() );
or.addChild( expressions.pop() );
expressions.push( or );
}
current = expressions.pop();
}
}
}
return current;
}
@Override
protected Object map(Admin traverser) {
Object ans = null;
// Execute the operations
Stack<Object> runStack = new Stack<Object>();
for (PixyDatum op : operations) {
switch (op.getType()) {
case NUMBER:
runStack.push(op.getNumber());
break;
case STRING:
runStack.push(op.getString());
break;
case SPECIAL_ATOM:
if (op.isAtomAPipeVar()) {
String namedStep = op.getAtomVarName();
Object curEnd;
if (namedStep.equals("")) {
curEnd = traverser.get();
} else {
curEnd = this.getNullableScopeValue(null, namedStep, traverser);
}
Object item = convertToRuntimeObject(namedStep, curEnd);
runStack.push(item);
} else if (op.isTrue()) {
runStack.push(Boolean.TRUE);
} else if (op.isFail()) {
runStack.push(Boolean.FALSE);
} else {
runStack.push(calculate(op.getAtom(), runStack));
}
break;
case RELATION:
case LIST:
case VARIABLE:
default:
throw new PixyException(PixyErrorCodes.INTERNAL_ERROR, "Unhandled operation: " + op + ". Run stack: " + runStack);
}
}
if (runStack.size() == 1) {
ans = runStack.pop();
} else {
throw new PixyException(PixyErrorCodes.INTERNAL_ERROR, "Internal error. Operations " + operations + " left run stack with " + runStack);
}
return ans;
}
/**
* Returns the TreeStateNode identified by path. This mirrors
* the behavior of getNodeForPath, but tries to take advantage of
* path if it is an instance of AbstractTreePath.
*/
private TreeStateNode getNodeForPath(TreePath path,
boolean onlyIfVisible,
boolean shouldCreate) {
if(path != null) {
TreeStateNode node;
node = getMapping(path);
if(node != null) {
if(onlyIfVisible && !node.isVisible())
return null;
return node;
}
// Check all the parent paths, until a match is found.
Stack<TreePath> paths;
if(tempStacks.size() == 0) {
paths = new Stack<TreePath>();
}
else {
paths = tempStacks.pop();
}
try {
paths.push(path);
path = path.getParentPath();
node = null;
while(path != null) {
node = getMapping(path);
if(node != null) {
// Found a match, create entries for all paths in
// paths.
while(node != null && paths.size() > 0) {
path = paths.pop();
node.getLoadedChildren(shouldCreate);
int childIndex = treeModel.
getIndexOfChild(node.getUserObject(),
path.getLastPathComponent());
if(childIndex == -1 ||
childIndex >= node.getChildCount() ||
(onlyIfVisible && !node.isVisible())) {
node = null;
}
else
node = (TreeStateNode)node.getChildAt
(childIndex);
}
return node;
}
paths.push(path);
path = path.getParentPath();
}
}
finally {
paths.removeAllElements();
tempStacks.push(paths);
}
// If we get here it means they share a different root!
// We could throw an exception...
}
return null;
}