数据结构
3.请编程完成泛型类GenericStack(栈),GenericStack的基本功能设计要求:创建栈、出栈、入栈、获取栈顶元素、判栈空,并写出全部测试类。 public class GenericStack<T> {private List<T> stack;
public GenericStack() {
stack = new ArrayList<>();
}
public void push(T item) {
stack.add(item);
}
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.remove(stack.size() - 1);
}
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.get(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class GenericStackTest {
@Test
public void testStackOperations() {
GenericStack<Integer> stack = new GenericStack<>();
assertTrue(stack.isEmpty());
stack.push(1);
assertFalse(stack.isEmpty());
assertEquals(1, (int) stack.peek());
stack.push(2);
assertEquals(2, (int) stack.peek());
assertEquals(2, (int) stack.pop());
assertEquals(1, (int) stack.pop());
assertTrue(stack.isEmpty());
}
}
该泛型类GenericStack实现了栈的基本功能,包括创建栈、出栈、入栈、获取栈顶元素和判断栈空。测试类GenericStackTest使用JUnit测试了栈的各项操作,确保其功能正常。 以下是泛型类GenericStack的实现以及测试类GenericStackTest的代码:
泛型类GenericStack的实现
java
import java.util.ArrayList;
// 泛型栈类
public class GenericStack<T> {
private ArrayList<T> stack;
// 创建空栈
public GenericStack() {
stack = new ArrayList<>();
}
// 入栈
public void push(T item) {
stack.add(item);
}
// 出栈
public T pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stack.remove(stack.size() - 1);
}
// 获取栈顶元素
public T peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stack.get(stack.size() - 1);
}
// 判栈空
public boolean isEmpty() {
return stack.isEmpty();
}
}
测试类GenericStackTest
java
public class GenericStackTest {
public static void main(String[] args) {
// 创建泛型栈
GenericStack<Integer> stack = new GenericStack<>();
// 入栈
stack.push(1);
stack.push(2);
stack.push(3);
// 获取栈顶元素并出栈
System.out.println("栈顶元素:" + stack.peek());
System.out.println("出栈元素:" + stack.pop());
// 判断栈是否为空
System.out.println("栈是否为空:" + stack.isEmpty());
// 出栈直至栈空
while (!stack.isEmpty()) {
System.out.println("出栈元素:" + stack.pop());
}
// 判断栈是否为空
System.out.println("栈是否为空:" + stack.isEmpty());
}
}
以上代码实现了泛型类GenericStack和测试类GenericStackTest。在测试类中,我们对栈的入栈、出栈、获取栈顶元素、判栈空等操作进行了测试,并输出了相应的结果。
页:
[1]