定义辅助栈分别保存最大值、最小值。
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[n];
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());
}
}