队列
-
队列,又称为伫列(queue),计算机科学中的一种抽象资料型别,是先进先出(FIFO, First-In-First-Out)的线性表。在具体应用中通常用链表或者数组来实现。队列只允许在后端(称为rear)进行插入操作,在前端(称为front)进行删除操作。 队列的操作方式和堆栈类似,唯一的区别在于队列只允许新数据在后端进行添加。
顺序队列
-
用数组实现的队列叫作顺序队列 -
代码实现 class ArrayQueue{
private Object[] objects;
private int count = 0;
private int head = 0;
private int tail = 0;
public ArrayQueue(int capacity){
this.objects = new Object[capacity];
this.count = capacity;
}
public boolean isEmpty(){
return head == tail;
}
public boolean isFull(){
return (tail + 1) % count == head;
}
public void enqueue(Object object){
if (!isFull()){
objects[tail] = object;
tail++;
}
}
public Object dequeue(){
Object res = null;
if (!isEmpty()){
res = objects[head];
head++;
}
return res;
}
}
链式队列
-
用链表实现的队列叫作链式队列 -
代码实现 class LinkedQueue {
private static class Node {
private Object data;
private Node next;
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
}
private Node head = null;
private Node tail = null;
public boolean isEmpty(){
return head == null;
}
public void enqueue(Object object){
if (tail == null){
Node newNode = new Node(object,null);
head = newNode;
tail = newNode;
}else {
tail.next = new Node(object,null);
tail = tail.next;
}
}
public Object dequeue(){
Object res = null;
if (!isEmpty()){
res = head.data;
head = head.next;
}else {
tail = null;
}
return res;
}
}
利用栈实现队列
-
借助于栈来实现队列 -
代码实现 class BaseStackQueue{
private Stack<Object> stack1;
private Stack<Object> stack2;
public BaseStackQueue(){
this.stack1 = new Stack<>();
this.stack2 = new Stack<>();
}
public boolean isEmpty(){
return stack1.isEmpty() && stack2.isEmpty();
}
public void enqueue(Object object){
stack1.push(object);
}
public Object dequeue(){
Object res = null;
if (!isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
res = stack2.pop();
}
return res;
}
}
|