问题:用链表实现一个先进先出的队列
分析:
1、链表实现,必须有一个节点能够装数据和下一个节点的指针(引用)
2、队列必须要有队首、队尾指针和记录当前队列大小的整型数
3、入队:往队尾加,队尾的下一个指针指向新元素,随后移动队尾指针指向新元素
4、出队:取出队首数据,移动队首指针指向队首的下一个元素
5、边界问题考虑
实现
1、节点类
/**
* 队列结点
*
* @author zab
* @date 2021-01-27 11:13
*/
public class Node {
private Node next;
private Object object;
public Node(Node next, Object object) {
this.next = next;
this.object = object;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
2、队列类
/**
* 简单队列
*
* @author zab
* @date 2021-01-27 11:03
*/
public class MyQueue {
private Node head;
private Node tail;
private int size;
public MyQueue() {
this.head = null;
this.tail = null;
this.size = 0;
}
public boolean in(Object o) {
//1、队列没有元素的情况
if (size == 0) {
head = new Node(null, o);
tail = head;
size++;
return true;
}
//2、如果队列有元素
Node newTailNode = new Node(null, o);
tail.setNext(newTailNode);
tail = newTailNode;
size++;
return true;
}
public Object out() {
//1、队列没有元素的情况
if (size == 0) {
return null;
}
//2、如果队列有1个元素
if (size == 1) {
Object o = head.getObject();
head = tail = null;
size--;
return o;
}
Object o = head.getObject();
head = head.getNext();
size--;
return o;
}
public int getSize() {
return size;
}
}
3、测试类
public class MyQueueTest {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.in(1);
myQueue.in(2);
myQueue.in(3);
myQueue.in(4);
Object out = myQueue.out();
Object out1 = myQueue.out();
Object out2 = myQueue.out();
Object out3 = myQueue.out();
Object out4 = myQueue.out();
System.out.println(out);
System.out.println(out1);
System.out.println(out2);
System.out.println(out3);
System.out.println(out4);
}
}
4、结果
1
2
3
4
nullProcess finished with exit code 0
可以看到,一个元素出队后,队列是2-->3-->4-->null
只剩最后一个元素时,是head和tail都指向4
当全部出队的时候,head和tail都指向null,这里得益于只有一个节点的出队方法边界处理。