1.代码:
package yrx;
public class LinkedQueue {
/**
* An inner class.
*/
class Node {
/**
* The data
*/
int data;
/**
* The reference to the next node.
*/
Node next;
/**
****************
* The constructor.
*
* @param paraValue The data.
*****************
*/
public Node(int paraValue) {
data = paraValue;
next = null;
}// Of the constructor
}// Of class Node
/**
* The header of queue.
*/
Node header;
/**
* The tail of the queue.
*/
Node tail;
/**
**************
* Construct an empty sequential list.
**************
*/
public LinkedQueue() {
header = new Node(-1);
// header.next=null;构造函数里已经有了,不用再写
tail = header;
}// Of the first constructor
/**
**********************
* Enqueue.
*
* @param paraValue The value of the new node.
**********************
*/
public void enqueue(int paraValue) {
Node tempNode = new Node(paraValue);
tail.next = tempNode;
tail = tempNode;
}// Of enqueue
/**
**********************
* Dequeue.
*
* @return The value at the header
**********************
*/
public int dequeue() {
if (header == tail) {// 队列为空
System.out.println("No element in the queue");
return -1;
} // Of if
int resultValue = header.next.data;
header.next = header.next.next;
// The queue becomes empty(出队列后,若队列为空,则需要修改队尾指针)
if (header.next == null) {
tail = header;
} // Of if
return resultValue;
}// Of dequeue
/**
**********************
* Overrides the method claimed in Object, the superclass of any class.
**********************
*/
public String toString() {
String resultString = "";
if (header.next == null) {
return "empty";
} // Of if
Node tempNode = header.next;
while (tempNode != null) {
resultString += tempNode.data + ",";
tempNode = tempNode.next;
} // Of while
return resultString;
}// Of toString
/**
**********************
* The entrance of the program.
*
* @param args Not used now
**********************
*/
public static void main(String args[]) {
LinkedQueue tempQueue = new LinkedQueue();
System.out.println("Initialized, the list is: " + tempQueue.toString());
for (int i = 0; i < 5; i++) {
tempQueue.enqueue(i + 1);
} // Of for i
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
tempQueue.dequeue();
System.out.println("Dequeue, the queue is: " + tempQueue.toString());
int tempValue;
for (int i = 0; i < 5; i++) {
tempValue = tempQueue.dequeue();
System.out.println("Looped delete " + tempValue + ", the new queue is: " + tempQueue.toString());
} // Of for i
for (int i = 0; i < 3; i++) {
tempQueue.enqueue(i + 10);
} // Of for i
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
}// Of main
}// Of class LinkedQueue
2.运行结果:
3.注意
a.对于队列,入队操作在队尾,出队操作在队首;
b.一般设置一个头结点,使第一个结点的操作与其余节点相同,更加方便;
c.当有尾指针时,头指针等于尾指针代表队列为空;