import java.util.Arrays;
class SeqStack{
// 存储栈的元素的数组
private T[] stack;
// top表示栈顶的位置
private int top;
public SeqStack(){
this(10);
}
public SeqStack(int size){
this.stack = (T[])new Object[size];
this.top = 0;
}
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 int pop(){
if(empty())
return 0;
this.top--;
if(this.top < this.stack.length/2){
this.stack = Arrays.copyOf(this.stack, this.stack.length/2);
}
}
public T top(){
return this.stack[this.top - 1];
}
public boolean full(){
return this.top == this.stack.length;
}
public boolean empty(){
return this.top == 0;
}
import java.util.Arrays;
/**
-
循环队列 特点:先入先出、后入后出
*/
class Queue{
// 存储队列元素的数组
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 = this.rear = 0;
}
/**
- 入队操作
- @param val
/
public void offer(E val){
if(full()){
// 扩容
E[] newQue = Arrays.copyOf(this.que,
this.que.length2);
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.rear = index;
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;
}
}
- 默认构造队列,初始大小是10