jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack

    科技2022-08-07  100

    定义IntegerStack接口,用于描述一个存放Integer元素的栈的常见方法:

    public Integer push(Integer item); //如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item。 public Integer pop(); //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null public Integer peek(); //获得栈顶元素,如果为空,则返回null. public boolean empty(); //如果为空返回true public int size(); //返回栈中元素个数

    定义IntegerStack的实现类ArrayIntegerStack,内部使用数组实现。创建时,可指定内部数组大小。

    main方法说明

    输入n,建立可包含n个元素的ArrayIntegerStack对象输入m个值,均入栈。每次入栈均打印入栈返回结果。输出栈顶元素,输出是否为空,输出size使用Arrays.toString()输出内部数组中的值。输入x,然后出栈x次,每次出栈均打印。输出栈顶元素,输出是否为空,输出size使用Arrays.toString()输出内部数组中的值。

    思考:

    如果IntegerStack接口的实现类内部使用ArrayList来存储元素,怎么实现?测试代码需要进行什么修改?

    输入样例

    5 3 1 2 3 2

    输出样例

    1 2 3 3,false,3 [1, 2, 3, null, null] 3 2 1,false,1 [1, 2, 3, null, null]

    答案

    import java.util.Arrays; import java.util.Scanner; interface IntegerStack { public Integer push(Integer item); //如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item public Integer pop(); //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null public Integer peek(); //获得栈顶元素,如果为空,则返回null public boolean empty(); //如果为空返回true public int size(); //返回栈中元素个数 } class ArrayIntegerStack implements IntegerStack{ private Integer[] arr; private int top = 0; public ArrayIntegerStack(int n){ arr = new Integer[n]; Arrays.fill(arr, null); } public ArrayIntegerStack(){} @Override public String toString() { return Arrays.toString(arr); } @Override public Integer push(Integer item) { if (item == null || arr.length == top){ return null; } arr[top++] = item; return item; } @Override public Integer pop() { if (top == 0){ return null; } return arr[--top]; } @Override public Integer peek() { if (top == 0){ return null; } return arr[top - 1]; } @Override public boolean empty() { return top == 0; } @Override public int size() { return top; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); ArrayIntegerStack ais = new ArrayIntegerStack(n); int m = scanner.nextInt(); while(m-- > 0){ int item = scanner.nextInt(); System.out.println(ais.push(item)); } System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size()); System.out.println(ais); int x = scanner.nextInt(); while(x-- > 0){ System.out.println(ais.pop()); } System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size()); System.out.println(ais); } }
    Processed: 0.018, SQL: 8