队列的实现
相对于栈的先进后出的特性来说,队列恰恰相反,是先进先出。同样,对于队列的实现可以通过链表和数组进行实现。下面是由链表实现的方法。
public class LinkQueueClone {
private Node front;
private Node tail;
private int size;
public LinkQueueClone() {
this.front = new Node(0);
this.tail = new Node(0);
}
/**
* 入队
*
* @param data
*/
public void push(int data) {
Node newNode = new Node(data);
Node temp = front;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
tail = newNode;
size++;
}
/**
* 出队
*
* @return
*/
public Integer pull() {
if (front.next == null) {
System.out.println("队列为空");
return null;
}
Node firstNode = front.next;
front.next = firstNode.next;
size--;
return firstNode.data;
}
/**
* 遍历队列
*/
public void traverse() {
Node temp = front;
while (temp.next != null) {
temp = temp.next;
System.out.println(temp.data + "\t");
}
}
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
}