提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
队列是一种重要且常见的数据结构,其特点是先进先出,可以用来解决很多复杂问题
提示:以下是本篇文章正文内容,下面案例可供参考
一、基本思想
利用链表来实现队列,主要就是注意实现队列先进先出的特点,其重点在于怎么进,和怎么出。
插入元素的时候,我们考虑从末端插入,出队的时候,从头部取出,由此可以知道需要一个head和一个last,利用这两个指针来进行插入和取出。
在插入时,我们考虑到last是否为空,为空时说明队列中没有元素。
取出时,我们也考虑队列是否为空,同时还要考虑队列是否只剩最后一个元素,因为只剩最后一个元素时,取出后队列将为空,同时让head.next指向时也容易产生空指针异常,需要注意。同时,只剩一个元素还要取出时,我们要让last = null,这样是为了再次插入时不出错。
二、代码实现
代码如下(示例):
package Queue;
import java.util.Iterator;
public class LinkedQueue<T> implements Iterable<T> {
private Node head;
private Node last;
private int N;
public LinkedQueue() {
head = new Node(null,null);
last = null;
N = 0;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
public class MyIterator implements Iterator<T>{
@Override
public boolean hasNext() {
return head.next != null;
}
@Override
public T next() {
Node t = head.next;
head = head.next;
return t.item;
}
}
public class Node {
private T item;
private Node next;
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
}
public boolean isEmpty(){
return N == 0;
}
public int size(){
return N;
}
//取出元素
public T dequeue(){
if (isEmpty()){
return null;
}
Node oldfirst = head.next;
if (oldfirst.next != null) {
head.next = head.next.next;
}else {
head.next = null;
last = null;
}
N--;
return oldfirst.item;
}
//插入一个节点
public void enqueue(T t){
if (last == null){
last = new Node(t,null);
head.next = last;
}else {
Node oldlast = last;
last = new Node(t,null);
oldlast.next = last;
}
N++;
}
public static void main(String[] args) {
LinkedQueue<String> linkedQueue = new LinkedQueue<>();
linkedQueue.enqueue("张三丰");
linkedQueue.enqueue("张无极");
linkedQueue.enqueue("张帅帅");
linkedQueue.enqueue("顾璨");
for (String str:linkedQueue){
System.out.println(str);
}
}
}
注意记得在LinkedQueue构造方法中为head,last,N初始化(一开始我漏了这个),最后结果如下: