1.写MyStack类,实现栈功能,要求在类中使用ArrayList保存数据。写MyStackTest类对栈功能进行测试。
时间: 2024-04-14 18:07:10 浏览: 140
MyStack类的代码如下:
```java
import java.util.ArrayList;
public class MyStack {
private ArrayList<Integer> stack;
public MyStack() {
stack = new ArrayList<>();
}
public void push(int x) {
stack.add(x);
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stack.remove(stack.size() - 1);
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stack.get(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
public int size() {
return stack.size();
}
}
```
MyStackTest类的代码如下:
```java
public class MyStackTest {
public static void main(String[] args) {
MyStack stack = new MyStack();
// 测试push方法
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack size after push: " + stack.size());
// 测试pop方法
System.out.println("Pop value: " + stack.pop());
System.out.println("Pop value: " + stack.pop());
System.out.println("Stack size after pop: " + stack.size());
// 测试peek方法
System.out.println("Peek value: " + stack.peek());
System.out.println("Stack size after peek: " + stack.size());
// 测试isEmpty方法
System.out.println("Stack is empty: " + stack.isEmpty());
stack.pop();
System.out.println("Stack is empty: " + stack.isEmpty());
}
}
```
输出结果如下:
```
Stack size after push: 3
Pop value: 3
Pop value: 2
Stack size after pop: 1
Peek value: 1
Stack size after peek: 1
Stack is empty: false
Stack is empty: true
```
阅读全文