队列的特点:先进先出
使用链表实现队列非常简单,成员变量只需要定义一个链表节点。先进去的数据放在链表的头部,后进去的数据依次放在链表尾部。每次出队列的时候只需要把头部的数据获取就可以了,然后node.next=node.next.next,删除原先的链表节点。
代码如下:
public class LinkQueue {
private Node front;
private int size;
public LinkQueue(){
this.front = new Node(0);
}
public void push(int val){
Node newNode = new Node(val);
Node temp = front;
while (temp.next!=null){
temp=temp.next;
}
temp.next=newNode;
size++;
}
public int poll(){
if (front.next==null){
throw new RuntimeException("队列已空");
}
Node firstNode = front.next;
front.next=front.next.next;
size--;
return firstNode.data;
}
public void traverse(){
Node temp = front.next;
while (temp!=null){
System.out.print(temp.data+"\t");
temp=temp.next;
}
}
public int size(){
return size;
}
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);
linkQueue.push(4);
linkQueue.push(5);
System.out.println("linkQueue.size = " + linkQueue.size);
linkQueue.traverse();
System.out.println("linkQueue.poll() = " + linkQueue.poll());
System.out.println("linkQueue.poll() = " + linkQueue.poll());
System.out.println("linkQueue.poll() = " + linkQueue.poll());
System.out.println("linkQueue.poll() = " + linkQueue.poll());
System.out.println("linkQueue.poll() = " + linkQueue.poll());
System.out.println("linkQueue.poll() = " + linkQueue.poll());
}
}