1 Node 类以前是 LinkdedList 的内嵌类, 这里重写了一遍. 访问控制的事情以后再说.
2 为方便操作, 空队列也需要一个节点. 这和以前的链表同理. 头节点的引用 (指针) 称为 header.
3 入队仅操作尾部, 出队仅操作头部.
代码
package datastructure.list;
public class LinkedQueue {
/**
* @author GDY
* @date 2021-12-22 04:53:51
*/
// 内部类
class Node {
int data;
Node next;
//构造方法
public Node(int paraValue) {
data = paraValue;
next = null;
}
}
//头指针
Node header;
//尾指针
Node tail;
//构造一个空队列
public LinkedQueue() {
header = new Node(-1);
// header.next=null;
tail = header;
}
// 入队
public void enquene(int paraValue) {
Node tempNode = new Node(paraValue);
tail.next = tempNode;
tail = tempNode;
}
// 出队
public int dequeue() {
if (header == tail) {
System.out.println("队列中已经没有元素了");
return -1;
}
int resultValue = header.next.data;
header.next = header.next.next;
// 当队列为空时
if (header.next == null) {
tail = header;
}
return resultValue;
}
// 重写toString方法
public String toString() {
String resultString = "";
if (header.next == null) {
return "empty";
}
Node tempNode = header.next;
while (tempNode != null) {
resultString += tempNode.data + ",";
tempNode = tempNode.next;
}
return resultString;
}
public static void main(String[] args) {
LinkedQueue tempQueue = new LinkedQueue();
System.out.println("最开始队列为:" + tempQueue.toString());
for (int i = 0; i < 5; i++) {
tempQueue.enquene(i + 1);
}
System.out.println("入队,队列为:" + tempQueue.toString());
tempQueue.dequeue();
System.out.println("出队,队列为:" + tempQueue.toString());
int tempValue;
for (int i = 0; i < 5; i++) {
tempValue = tempQueue.dequeue();
System.out.println("循环删除" + tempValue + ",新队列为:" + tempQueue.toString());
}
for (int i = 0; i < 3; i++) {
tempQueue.enquene(i + 10);
}
System.out.println("入队,队列为:" + tempQueue.toString());
}
}
运行结果
最开始队列为:empty
入队,队列为:1,2,3,4,5,
出队,队列为:2,3,4,5,
循环删除2,新队列为:3,4,5,
循环删除3,新队列为:4,5,
循环删除4,新队列为:5,
循环删除5,新队列为:empty
队列中已经没有元素了
循环删除-1,新队列为:empty
入队,队列为:10,11,12,
在下觉得声明的这个类使用泛型<E>会更好一点,之后会完善以下并给出代码