栈的构造:
import java.util.Arrays;
/**
* @author zhou
* @date 2021-5-7 8:12
*/
public class MyStack {
private int[] elements;
public MyStack(){
elements = new int[0];
}
public void show(){ // 打印 栈
System.out.println(Arrays.toString(elements));
}
public void push(int element) { // 入栈
int[] newArr = new int[elements.length + 1];
for (int i = 0; i < elements.length; i++) {
newArr[i] = elements[i];
}
newArr[elements.length] = element;
elements = newArr;
}
public int pop(){ // 出栈
if (elements.length == 0) {
throw new ArrayIndexOutOfBoundsException("Stack is empty");
}
// 取出数组最后一个元素
int element=elements[elements.length - 1];
int[] newArr = new int[elements.length - 1];
for (int i = 0; i < newArr.length; i++) {
newArr[i] = elements[i];
}
elements = newArr;
return element;
}
public int peek(){ // 显示栈的顶端元素
if (elements.length == 0) {
throw new ArrayIndexOutOfBoundsException("Stack is empty");
}
return elements[elements.length - 1];
}
public boolean isEmpty(){ // 判断栈是否为空
return elements.length == 0;
}
}
栈的测试类:
/**
* @author zhou
* @date 2021-5-7
* 测试类 测试MyStack 栈
*/
public class TestMyStack {
public static void main(String[] args) {
MyStack ms = new MyStack();
ms.push(11);
ms.push(22);
ms.push(33);
ms.push(16);
ms.show();
int pop = ms.pop();
System.out.println(pop);
ms.show();
System.out.println(ms.isEmpty());
System.out.println(ms.peek());
}
}
运行结果:
[11, 22, 33, 16]
16
[11, 22, 33]
false
33
队列的构造:
import java.util.Arrays;
/**
* @author zhou
* @date 2021-5-7 14:35
* 队列
*/
public class MyQueue {
int[] elements;
public MyQueue(){ // 初始化数组为0
elements = new int[0];
}
public void show(){
System.out.println(Arrays.toString(elements));
}
public void add(int element){ // 入队
int[] newArr = new int[elements.length + 1];
for (int i = 0; i < elements.length; i++) {
newArr[i] = elements[i];
}
newArr[elements.length] = element;
elements = newArr;
}
public void poll() { // 出队
if (elements.length == 0) {
throw new ArrayIndexOutOfBoundsException("Queue is empty");
}
int[] newArr = new int[elements.length - 1];
for (int i = 0; i < newArr.length; i++) {
newArr[i] = elements[i + 1];
}
elements = newArr;
}
public int peek() { // 查看队头元素
if (elements.length == 0) {
return -1;
}
return elements[0];
}
public boolean isEmpty(){
return elements.length == 0;
}
}
队列的测试类:
/**
* @author zhou
* @date 2021-5-7 14:38
* 用于测试手写队列
*/
public class TestQueue {
public static void main(String[] args) {
MyQueue mq = new MyQueue();
mq.add(22);
mq.add(5);
mq.add(66);
mq.add(12);
mq.add(33);
mq.show();
mq.poll(); // 出队
mq.show();
System.out.println(mq.isEmpty());
System.out.println(mq.peek());
}
}
运行结果:
[22, 5, 66, 12, 33]
[5, 66, 12, 33]
false
5