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

该博客介绍了如何实现一个基于数组的IntegerStack接口,包括push、pop、peek、empty和size等方法。示例展示了使用ArrayIntegerStack类的实例进行操作,如入栈、出栈、获取栈顶元素及检查栈的状态,并给出了使用ArrayList实现IntegerStack的思考。测试代码中,首先创建栈并入栈,然后输出栈顶元素、空栈状态和元素数量,最后进行出栈操作并再次检查栈的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义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方法说明

  1. 输入n,建立可包含n个元素的ArrayIntegerStack对象
  2. 输入m个值,均入栈。每次入栈均打印入栈返回结果。
  3. 输出栈顶元素,输出是否为空,输出size
  4. 使用Arrays.toString()输出内部数组中的值。
  5. 输入x,然后出栈x次,每次出栈均打印。
  6. 输出栈顶元素,输出是否为空,输出size
  7. 使用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.*;


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{
	public Integer [] array;
	private int len;
	public ArrayIntegerStack(int n) {
		this.array = new Integer[n];
		len=0;
	}
	public Integer push(Integer item) {
		if(item==null) {
			return null;
		}
		if(len==this.array.length) {
			return null;
		}
		array[len++]=item;
		return item;
	}
	public Integer pop() {
		if(len==0) {
			return null;
		}
		len--;
		return array[len];
	}
	public Integer peek() {
		if(len==0) {
			return null;
		}
		return array[len-1];
	}
	public boolean empty() {
		if(len==0) {
			return true;
		}
		else {
			return false;
		}
	}
	public int size() {
		return len;
	}
}

public class Main{
    public static void main(String [] args){
    	Scanner in=new Scanner(System.in);
    	int n = in.nextInt();
    	ArrayIntegerStack stack = new ArrayIntegerStack(n);
    	int m = in.nextInt();
    	for(int i=0;i<m;i++) {
    		int temp = in.nextInt();
    		System.out.println(stack.push(temp));
    	}
		System.out.println(stack.peek()+","+stack.empty()+","+stack.size());
		System.out.println(Arrays.toString(stack.array));
		int x = in.nextInt();
		for(int j = 0;j<x;j++) {
			System.out.println(stack.pop());
		}
		System.out.println(stack.peek()+","+stack.empty()+","+stack.size());
		System.out.println(Arrays.toString(stack.array));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值