- 示意图(队列横向,栈竖向好看;链表实现队列不用给初始化尺寸,不担心溢出)
- 代码
public class LinkedQueue{
Node front;
Node rear;
public LinkedQueue() {
this.front = null;
this.rear = null;
}
public boolean inQueue(int value) {
Node node = new Node(value);
if (front == null) {
front = node;
rear = front;
} else {
rear.next = node;
rear = node;
}
return true;
}
public int outQueue() {
if (front == null) {
System.out.println("当前队列为空");
return -1;
}
int data = front.data;
front = front.next;
return data;
}
public static void main(String[] args) {
LinkedQueue queue = new LinkedQueue();
queue.inQueue(1);
queue.inQueue(2);
queue.inQueue(3);
queue.outQueue();
while (queue.front != null) {
System.out.println(queue.front.data);
queue.front = queue.front.next;
}
}
}
class Node {
Node next;
int data;
public Node(int data) {
this.data = data;
}
}
- 结果
|