1.栈和队列
栈:先进后出
队列:先进先出
2.栈的基本操作
(1)初始值
private T[] element;
private int top;
(2)入栈
public void push(T value) {
if (top == element.length) {
element = Arrays.copyOf(element, element.length << 1);
}
element[top] = value;
top++;
(3)出栈
public void pop(T value) {
if (top == 0) {
return;
}
element[--top] = null;
}
(4)返回栈顶元素
public T peek() {
if (top == 0) {
throw new EmptyStackException();
}
return element[top - 1];
}
(5)两个栈模拟队列
public class twoStackToOneQueue {
public static<T> void twoStackToOneQueue(T[] arr){
Stack<T> stack1=new Stack<>();
Stack<T> stack2=new Stack<>();
for(int i=0;i<arr.length;i++){
stack1.push(arr[i]);
}
while(!stack1.isEmpty()){
T value=stack1.peek();
stack2.push(value);
stack1.pop();
}
while(!stack2.isEmpty()){
System.out.println(stack2.peek()+" ");
stack2.pop();
}
T value=stack1.peek();
stack2.push(value);
}
}
2.队列
(1)初始值
private T[] element;
private int size;
private static final int ININSIZE=10;
public MyQueue(){
element=(T[])new Object[ININSIZE] ;
}
(2)入队
public void push(T value) {
if (size == element.length) {
element = Arrays.copyOf(element, element.length *2);
}
element[size++]=value;
}
(3)出队
public void pop(T value){
if(size==0){
return;
}
for(int i=1;i<size;i++) {
element[i - 1] = element[i];
}
element[size-1]=null;
size--;
}