您的位置:首页 > 运维架构

实现包含min,max,push,pop函数的栈

2017-09-26 21:20 260 查看
定义辅助栈分别保存最大值、最小值。

import java.util.Scanner;
import java.util.Stack;

public class Test {

public static class myStack {
Stack <Integer> dataStk = new Stack<Integer>();
Stack <Integer> minStk = new Stack<Integer>();
Stack <Integer> maxStk = new Stack<Integer>();
public void push(int node) {
dataStk.push(node);
if(minStk.isEmpty() || minStk.peek()>node){
minStk.push(node);
}else{
minStk.push(minStk.peek());
}
if(maxStk.isEmpty() || maxStk.peek()<node){
maxStk.push(node);
}else{
maxStk.push(maxStk.peek());
}
}

public void pop() {
dataStk.pop();
minStk.pop();
maxStk.pop();
}

public int top() {
return dataStk.peek();
}

public int min() {
return minStk.peek();
}
public int max() {
return maxStk.peek();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int
;
myStack mystk = new myStack();
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
mystk.push(arr[i]);
}
mystk.pop();
System.out.println(mystk.max()+","+mystk.min());
}

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