1.队列
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
2.入队
- 创建一个新的节点
- 将新节点接在队尾
- 然后队尾指针指向新节点
public void enqueue(int paraValue) {
Node tempNode = new Node(paraValue);
tail.next = tempNode;
tail = tempNode;
}// of enqueue
3.出栈
- 首先判断队列是否为空
- 然后队列从队头开始出队
- 出队后,判断header的next是否为空,如果为空,这该队列为空,将tail=header
public int dequeue() {
if (header == tail) {
System.out.println("No element in the queue");
return -1;
}
int resultValue = header.next.data;
header.next = header.next.next;
if (header.next == null) {
tail = header;
}
return resultValue;
}// of dequeue
4.代码实现
package com.datastructure;
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);
tail = header;
}// of the first constructor
//入队,入队操作再队尾进行
//1.创建一个新节点,再将新节点接在队尾,将队尾指针指向新节点
public void enqueue(int paraValue) {
Node tempNode = new Node(paraValue);
tail.next = tempNode;
tail = tempNode;
}// of enqueue
//出队,出队操作再对头进行
//1.判断队列是否为空
public int dequeue() {
if (header == tail) {
System.out.println("No element in the queue");
return -1;
}
int resultValue = header.next.data;
header.next = header.next.next;
// 出队后,判断header的next是否为空,如果为空,这该队列为空,将tail=header
if (header.next == null) {
tail = header;
}
return resultValue;
}// of dequeue
public String toString() {
String resultString = "";
if (header.next == null) {
return "empty";
} // Of if
Node tempNode = header.next;
resultString += tempNode.data;
tempNode = tempNode.next;
while (tempNode != null) {
resultString += ", " + tempNode.data;
tempNode = tempNode.next;
} //of while
return resultString;
}//of toString
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