1.链队的基本实现
在链队进行操作的时候,入队仅能在尾部操作,出队在头部操作。注意在出队时若已空,需要将尾指针重置到头指针的位置去。
2.代码
package demo;
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
}// Of class LinkedQueue
运行结果:
3.总结
链队中一定要注意入队出队的位置,已经入队后哪个指针动的问题。在后面main中经过多次入队出队的测试,在队列元素出队的时候,一定判断是否队空,如果队空了的话,一定要将尾指针回到头指针的位置,否则在循环当中,队空以后还在输出,就出现越界数据出错的问题。