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

来源:互联网 发布:自学编程的app 编辑:程序博客网 时间:2024/05/18 00:15

定义辅助栈分别保存最大值、最小值。

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 stubScanner 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());}}


阅读全文
0 0