本题是实现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();
}
}
4 回答
慕侠2389804
TA贡献1719条经验 获得超6个赞
既然你要用stack来实现,还要用==来判断,那就应该push的时候做控制,让两个stack加入的对象是同一个。
public class MinStack {
Stack<Integer> minstack = new Stack<Integer>();
Stack<Integer> stack = new Stack<Integer>();
public MinStack() {
}
public void push(int x) {
Integer val = new Integer(x);
if(minstack.empty() || val <= minstack.peek())
minstack.push(val);
stack.push(val);
}
public void pop() {
if(minstack.peek()==(stack.peek()))
minstack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin(){
return minstack.peek();
}
}
达令说
TA贡献1821条经验 获得超6个赞
==是比较两个字符串引用的地址是否相同,即是否指向同一个对象,而equals方法则比较字符串的内容是否相同。
例如
String a = "abc";
String b = "abc";
a == b返回true,a.equals(b)同样返回true。
因为程序在运行时有一个字符串池,创建字符串时会先查找池中是否有相应的字符串,如果已经存在的话只需把引用指向它即可,如果没有则新建一个。
上例中创建a时,会在字符串池中首先创建一个"abc",然后a指向它;创建b时,由于"abc"已经存在,b直接指向它即可。
若改为:
String a = "abc";
String b = new String("abc");
则a == b返回false,a.equals(b)返回true。因为创建b时不管"abc"是否存在都会new一个新的"abc",从而a和b指向的字符创对象是不同的,因此返回false。
添加回答
举报
0/150
提交
取消