队列的特点是节点的排队次序和出队次序按入队时间先后确定,即先入队者先出队,后入队者后出队,即我们常说的FIFO(first in first out)先进先出。队列实现方式也有两种形式,基于数组和基于链表。 对于基于链表,因为链表的长度是随时都可以变的,实现起来比较简单,本文就以基于链表为例。
public class LinkQueue {
private ListNode front;
private ListNode rear;
private int size;
public LinkQueue() {
this.front = new ListNode(0);
this.rear = new ListNode(0);
}
/**
* 入队
*/
public void push(int value) {
ListNode newNode = new ListNode(value);
ListNode temp = front;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
rear = newNode;
size++;
}
/**
* 出队
*/
public int pull() {
if (front.next == null) {
System.out.println("队列已空");
}
ListNode firstNode = front.next;
front.next = firstNode.next;
size--;
return (int) firstNode.value;
}
/**
* 遍历队列
*/
public void traverse() {
ListNode temp = front.next;
while (temp != null) {
System.out.print(temp.value + "\t");
temp = temp.next;
}
}
}