节点类
package queue.demo;
public class Node {
private Object data;
private Node nextNode;
private Node prevNode;
public Node(Object data) {
super();
this.data = data;
}
public Node(Object data, Node prevNode, Node nextNode) {
super();
this.data = data;
this.nextNode = nextNode;
this.prevNode = prevNode;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getPrevNode() {
return prevNode;
}
public void setPrevNode(Node prevNode) {
this.prevNode = prevNode;
}
}
队列类
package queue.demo;
public class Queue {
int length = 5;
int size = 0;
Node first;
Node last;
// 入队
public void add(String value) {
if (size == length) {
System.out.println("队列以满,无法添加");
return;
}
Node newNode = new Node(value, last, null);
Node temp = last;
last = newNode;
if (temp == null) {
first = newNode;
} else {
temp.setNextNode(newNode);
}
size++;
}
// 出队,先进先出
public String removeFirst() {
if (size == 0) {
System.out.println("空队列,无法出队");
return null;
}
Node temp = first;
first = first.getNextNode();
size--;
return (String) temp.getData();
}
}
执行测试类
package queue.demo;
public class Main {
public static void main(String[] args) {
Queue q = new Queue();
q.add("a");
System.out.println("进队a");
q.add("b");
System.out.println("进队b");
q.add("c");
System.out.println("进队c");
q.add("d");
System.out.println("进队d");
q.add("e");
System.out.println("进队e");
q.add("f");
System.out.println("进队f");
System.out.println("出队: " + q.removeFirst());
System.out.println("出队: " + q.removeFirst());
System.out.println("出队: " + q.removeFirst());
System.out.println("出队: " + q.removeFirst());
System.out.println("出队: " + q.removeFirst());
System.out.println("出队: " + q.removeFirst());
}
}
执行结果
进队a
进队b
进队c
进队d
进队e
队列以满,无法添加
进队f
出队: a
出队: b
出队: c
出队: d
出队: e
空队列,无法出队
出队: null