您的位置:首页 > 编程语言 > Java开发

实现getMin功能的栈

2016-07-10 16:41 267 查看
第一种方式:

import java.util.Stack;
public class MyStack1 {
public static void main(String[] args) {
MyStack1Real myStack1Real = new MyStack1Real();
for (int i = 0; i < 10; i++) {
myStack1Real.push(i);
}
myStack1Real.push(-1);
System.out.println(myStack1Real.getMin());
}
}

class MyStack1Real {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;

public MyStack1Real() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}

public void push(int newNum) {
if (stackMin.isEmpty()) {
stackMin.push(newNum);
} else if (newNum <= this.getMin()) {
stackMin.push(newNum);
}
stackData.push(newNum);
}

public int pop() {
if (this.stackData.peek() == this.stackMin.peek()) {
this.stackData.pop();
return this.stackMin.pop();
} else {
return this.stackMin.pop();
}
}

public int getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("your stack is empty!");
} else {
return this.stackMin.peek();
}
}

}


第二种方式:
package stackAndQueue;

import java.util.Stack;

public class MyStack2 {
public static void main(String[] args) {
MyStack1Real myStack1Real = new MyStack1Real();
for (int i = 0; i < 10; i++) {
myStack1Real.push(i);
}
myStack1Real.push(-8);
System.out.println(myStack1Real.getMin());
}
}

class MyStack2Real {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;

public MyStack2Real() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}

public void push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackData.push(newNum);
this.stackMin.push(newNum);
} else if (newNum <= this.getMin()) {
this.stackData.push(newNum);
this.stackMin.push(newNum);
} else {
this.stackData.push(newNum);
this.stackMin.push(this.stackMin.peek());
}
}

public int pop(int newNum) {
this.stackMin.pop();
return this.stackData.pop();
}

public int getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("your stack is empty");
} else {
return stackMin.peek();
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java getMin