压栈是数据第一个进入,最后一个出来,简称FILO,first in last out
队列是数据第一个进入,第一个出来,简称FIFO,first in first out
1、压栈
public class Stack<T> {
/**
* 维护一个超级数组
*/
SuperArray<T> superArray = new SuperArray<>();
/**
* 入(压)栈的方法
*/
public void put(T data){
superArray.add(data);
}
/**
* 弹栈的方法
* @return
*/
public T pop(){
if (superArray.size() >= 1){
T temp = superArray.get(superArray.size()-1);
superArray.delete(superArray.size()-1);
return temp;
}
return null;
}
}
2、队列
public class Queue<T> {
/**
* 维护一个超级数组
*/
SuperArray<T> superArray = new SuperArray<>();
/**
* 入(压)栈的方法
*/
public void put(T data){
superArray.add(data);
}
/**
* 弹栈的方法
* @return
*/
public T take(){
if (superArray.size() >= 1){
T temp = superArray.get(0);
superArray.delete(0);
return temp;
}
return null;
}
public boolean isNotEmpty() {
// 大于0不是空返回true,小于0是空返回false
return superArray.size() > 0;
}
}
3、测试类
public class Test {
public static void main(String[] args) {
/**
* 弹出的顺序为4/3/2/1/null
*/
Stack<Integer> stack = new Stack<>();
stack.put(1);
stack.put(2);
stack.put(3);
stack.put(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
/**
* 弹出的顺序为1/2/3/4/null
*/
Queue<Integer> queue = new Queue<>();
queue.put(1);
queue.put(2);
queue.put(3);
queue.put(4);
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
}
}