本题是实现stack相关内容。
最早的时候写的代码如下,加粗部分的判断用==连接,
if(minstack.peek()==(stack.peek())
但是结果不正确,报告如下
Input:
["MinStack","push","push","push","push","pop","getMin","pop","getMin","pop","getMin"]
[[],[512],[-1024],[-1024],[512],[],[],[],[],[],[]]
Output:
["constructor","null","null","null","null","null","-1024","null","-1024","null","-1024"]
Expected:
["constructor","null","null","null","null","null","-1024","null","-1024","null","512"]
之后将加粗部分改为:
if(minstack.peek().equals(stack.peek()))
使用equals()连接,答案就是正确的了。
新人入码坑,求老师们指点一二这是为何?
另:这个结果报告是怎么看的,有点看不懂,是和二叉树有关的写法?求各位前辈指教!
谢谢!
附源码如下:
public class MinStack {
Stack<Integer> minstack = new Stack<Integer>();
Stack<Integer> stack = new Stack<Integer>();
public MinStack() {
}
public void push(int x) {
if(minstack.empty() || x <= minstack.peek())
minstack.push(x);
stack.push(x);
}
public void pop() {
**if(minstack.peek()==(stack.peek()))**
minstack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin(){
return minstack.peek();
}
}
Since you want to use stack to implement it and use == to judge, you should control it when pushing so that the objects added to the two stacks are the same.
== compares references, and equals compares values.
== is to compare whether the addresses referenced by two strings are the same, that is, whether they point to the same object, while the equals method compares whether the contents of the strings are the same.
For example
a == b returns true, a.equals(b) also returns true.
Because the program has a string pool when it is running, when creating a string, it will first check whether there is a corresponding string in the pool. If it already exists, just point the reference to it. If not, create a new one.
In the above example, when a is created, an "abc" will be created first in the string pool, and then a points to it; when b is created, since "abc" already exists, b can point directly to it.
If changed to:
Then a == b returns false, and a.equals(b) returns true. Because when b is created, a new "abc" will be created regardless of whether "abc" exists, so the character creation objects pointed to by a and b are different, so false is returned.