在这里插入代码片
队列的特点是节点的排队次序和出队次序按入队时间先后确定,即先入队者先出队,后入队者后出队,即我们常说的FIFO(first in first out)先进先出。队列实现方式也有两种形式,基于数组和基于链表。 对于基于链表,因为链表的长度是随时都可以变的,实现起来比较简单。如果是基于数组的,会有点麻烦,我们将其放在黄金挑战里再看,这里只看一下基于链表实现的方法。
入队:
出队:
/**
* @author NuoMi
*/
public class LinkQueue {
private Node front;
private Node rear;
private int size;
public LinkQueue() {
this.front = new Node(0);
this.rear = new Node(0);
}
//入队
public void push(int value) {
Node newNode = new Node(value);
Node 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("队列为空");
}
Node firstNode = front.next;
front.next = firstNode.next;
size--;
return firstNode.data;
}
public void traverse() {
Node temp = front.next;
while (temp != null) {
System.out.print(temp.data + "\t");
temp = temp.next;
}
}
static class Node {
public int data;
public Node next;
public Node (int data) {
this.data = data;
}
}
public static void main(String[] args) {
LinkQueue linkQueue = new LinkQueue();
linkQueue.push(1);
linkQueue.push(2);
linkQueue.push(3);
System.out.println("第一个出队的元素为:" + linkQueue.pull());
System.out.println("队列中的元素为:");
linkQueue.traverse();
}
}