1 链队列的基本实现
代码
package demo1;
public class LinkedQueue {
class Node {
int data;
Node next;
// 节点定义
public Node(int paraValue) {
data = paraValue;
next = null;
}// Of the constructor
}// Of class Node
Node header;// 头指针
Node tail;// 尾指针
// 建立一个空的链表
public LinkedQueue() {
header = new Node(-1);
// header.next = null; 多余的一句??好像重复了啊
tail = header;
}// Of the first constructor
/*
* ******** 入队 ********
*/
public void enqueue(int paraValue) {
Node tempNode = new Node(paraValue);
tail.next = tempNode;
tail = tempNode;
}// Of enqueue
/*
* ******** 入队 ********
*/
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;
// 如果全部出队
if (header.next == null) {
tail = header;
} // Of if
return resultValue;
}// Of dequeue
/*
* ******** 重写toString ********
*/
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
/*
* main
*/
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
}
运行结果