栈和队列是非常基础但又十分重要十分常用的数据结构。栈的先入后出和队列的先入先入特性在软件工程中的应用非常广泛。以下为java版基于数组的简单实现。
/**
* desc : 栈的数组实现
* Created by tiantian on 2018/9/1
*/
public class Stack {
private Object[] value;
private int top = -1;
private int size;
public Stack(int size) {
value = new Object[size];
this.size = size;
}
public boolean isEmpty() {
return top == 0;
}
public void push(Object val) {
if (top == size) {
throw new StackOverflowError();
}
value[++top] = val;
}
public Object pop() {
if (top < 0) {
throw new EmptyStackException();
}
Object obj = value[top];
top--;
return obj;
}
}
/**
* desc : 队列的数组实现
* Created by tiantian on 2018/9/1
*/
public class Queue {
private Object[] queue;
private int length;
private int head = 0;
private int tail = 0;
public Queue(int len) {
this.length = len;
queue = new Object[len];
}
public void enQueue(Object obj) {
if (tail == length) {
tail = 0;
}
queue[tail++] = obj;
}
public Object deQueue() {
if (queue[head] == null) {
return null;
}
Object temp = queue[head];
if (head == length) {
head = 0;
} else {
head++;
}
return temp;
}
}