modify code

master
algorithmzuo 3 years ago
parent d3b40a743f
commit 25f140ff20

@ -9,35 +9,33 @@ public class Code05_GetMinStack {
private Stack<Integer> stackMin;
public MyStack1() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
stackData = new Stack<Integer>();
stackMin = new Stack<Integer>();
}
public void push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum <= this.getmin()) {
this.stackMin.push(newNum);
if (stackMin.isEmpty() || newNum <= this.getmin()) {
stackMin.push(newNum);
}
this.stackData.push(newNum);
stackData.push(newNum);
}
public int pop() {
if (this.stackData.isEmpty()) {
if (stackData.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
int value = this.stackData.pop();
if (value == this.getmin()) {
this.stackMin.pop();
int value = stackData.pop();
if (value == getmin()) {
stackMin.pop();
}
return value;
}
public int getmin() {
if (this.stackMin.isEmpty()) {
if (stackMin.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
return this.stackMin.peek();
return stackMin.peek();
}
}
@ -46,35 +44,32 @@ public class Code05_GetMinStack {
private Stack<Integer> stackMin;
public MyStack2() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
stackData = new Stack<Integer>();
stackMin = new Stack<Integer>();
}
public void push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum < this.getmin()) {
this.stackMin.push(newNum);
if (stackMin.isEmpty() || newNum < getmin()) {
stackMin.push(newNum);
} else {
int newMin = this.stackMin.peek();
this.stackMin.push(newMin);
stackMin.push(stackMin.peek());
}
this.stackData.push(newNum);
stackData.push(newNum);
}
public int pop() {
if (this.stackData.isEmpty()) {
if (stackData.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
this.stackMin.pop();
return this.stackData.pop();
stackMin.pop();
return stackData.pop();
}
public int getmin() {
if (this.stackMin.isEmpty()) {
if (stackMin.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
return this.stackMin.peek();
return stackMin.peek();
}
}
@ -91,7 +86,7 @@ public class Code05_GetMinStack {
System.out.println("=============");
MyStack1 stack2 = new MyStack1();
MyStack2 stack2 = new MyStack2();
stack2.push(3);
System.out.println(stack2.getmin());
stack2.push(4);

Loading…
Cancel
Save