题目描述
实现一个特殊功能的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
输入描述:
第一行输入一个整数N,表示对栈进行的操作总数。
下面N行每行输入一个字符串S,表示操作的种类。
如果S为"push",则后面还有一个整数X表示向栈里压入整数X。
如果S为"pop",则表示弹出栈顶操作。
如果S为"getMin",则表示询问当前栈中的最小元素是多少。
输出描述:
对于每个getMin操作,输出一行表示当前栈中的最小元素是多少。
示例1
输入
6
push 3
push 2
push 1
getMin
pop
getMin
输出
1
2
解法一:两个栈
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int len = Integer.parseInt(br.readLine());
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
for(int i=0;i<len;i++){
String[] ss = br.readLine().trim().split(" ");
String str = ss[0];
if(str.equals("push")){
int num = Integer.parseInt(ss[1]);
s1.push(num);
if(s2.isEmpty()||s2.peek()>=num){
s2.push(num);
}
}else if(str.equals("pop")){
if(s1.isEmpty()){
throw new RuntimeException("没数据了");
}else if(s2.peek().equals(s1.peek())) {
s2.pop();
}
s1.pop();
}else{
if(!s2.isEmpty()) {
System.out.println(s2.peek());
}else {
throw new RuntimeException("没数据了");
}
}
}
}
}
ps:其中涉及Integer对象的比较值比较用a.equals(b)。但是假如值在-128-127时用==依然可以判断。
解法二:数据栈插入数据,min栈也插入
ps: 封装一下
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int len = Integer.parseInt(br.readLine());
MyStack ms = new MyStack();
for(int i=0;i<len;i++){
String[] ss = br.readLine().trim().split(" ");
String str = ss[0];
if(str.equals("push")){
int num = Integer.parseInt(ss[1]);
ms.push(num);
}else if(str.equals("pop")){
ms.pop();
}else{
System.out.println(ms.getMin());
}
}
}
}
class MyStack{
private Stack<Integer> s1;
private Stack<Integer> s2;
public MyStack(){
this.s1 = new Stack<>();
this.s2 = new Stack<>();
}
public void push(int num){
if(s2.isEmpty()){
s2.push(num);
}else if(num<s2.peek()){
s2.push(num);
}else{
int tmpmin = s2.peek();
s2.push(tmpmin);
}
s1.push(num);
}
public int pop() {
if(s1.isEmpty()){
throw new RuntimeException("没数据了");
}
s2.pop();
return s1.pop();
}
public int getMin(){
if(s1.isEmpty()){
throw new RuntimeException("没数据了");
}
return s2.peek();
}
}