栈:先进后出,后进先出
用泛型是按顺序栈结构
*SeqStack<>:<>叫做泛型参数列表,里面可以定义名字,实际上是一个类型占位符,
*你可以理解成,它代表用户指定的一个类型
class SeqStack<T>{
// 存储栈的元素的数组
private T[] stack;
// top表示栈顶的位置
private int top;
// 默认的构造函数,默认开辟10个位置空间
public SeqStack(){
this(10);
}
//用户可以指定栈的大小size
// @param size
public SeqStack(int size){
this.stack = (T[])new Object[size];
this.top = 0;
}
//入栈操作
//@param val
public void push(T val){
if(full()){
// 栈如果满了,要进行内存2倍扩容
this.stack = Arrays.copyOf(this.stack,
this.stack.length*2);
}
this.stack[this.top] = val;
this.top++;
}
// 出栈操作
public void pop(){
if(empty())
return;
this.top--;
if(this.top < this.stack.length/2){
this.stack = Arrays.copyOf(this.stack, this.stack.length/2);
}
}
//获取栈顶元素
//@return
public T top(){
return this.stack[this.top - 1];
}
//判断栈满
//@return
public boolean full(){
return this.top == this.stack.length;
}
//判断栈空
//@return
public boolean empty(){
return this.top == 0;
}
}
队列:先进先出,后进后出
class Queue<E> {
// 存储队列元素的数组
private E[] que;
// 表示队头的位置
private int front;
// 表示队尾的位置
private int rear;
/**
* 默认构造队列,初始大小是10
*/
public Queue() {
this(10);
}
/**
* 用户可以指定队列的大小size
*
* @param size
*/
public Queue(int size) {
this.que = (E[]) new Object[size];
this.front = 0;
}
/**
* 入队操作
* 入队从队尾入,从队头出
*
* @param val
*/
public void offer(E val) {
if (full()) {
E[] newque = Arrays.copyOf(this.que, this.que.length * 2);
int index = 0;
for (int i = this.front; i != this.rear; i = (i + 1) % this.que.length) {
newque[index++] = this.que[i];
this.front = 0;
this.que = newque;
}
this.que[this.rear] = val;
this.rear = (this.rear + 1) % this.que.length;
}
}
/**
* 出队操作,并把出队的元素的值返回
*/
public E poll() {
if (empty()) {
return null;
}
E front = this.que[this.front];
this.front = (this.front + 1) % this.que.length;
return front;
}
/**
* 查看队头元素
*
* @return
*/
public E peek() {
if (empty()) {
return null;
}
return this.que[this.front];
}
/**
* 判断队满
*
* @return
*/
public boolean full() {
return (this.rear + 1) % this.que.length == this.front;
}
/**
* 判断队空
*
* @return
*/
public boolean empty() {
return this.rear == this.front;
}
}