算法与数据结构(三):线性表之队列
博主会对算法与数据结构会不断进行更新,敬请期待,如有什么建议,欢迎联系。
线性表是最基本、最简单、也是最常用的一种数据结构。一个线性表是n个具有相同特性的数据元素的有限序列。
线性表分为:顺序表,链表,栈,队列。
队列属于线性表的一种,具有先进先出的特点,底层可以由数组或链表实现,在这里博主由链表进行了实现。相比于栈后进先出的特点,队列每次添加新值要放入尾结点,每次弹出值要从头结点取出,因此,要首先定义头结点和尾结点。
队列的实现代码如下:
package com.victor.linear;
import java.util.Iterator;
/**
* @Description: 队列
* @Author: victor
*/
public class Queue<T> implements Iterable<T> {
private Node head;
private Node last;
int N;
public Queue() {
head = new Node(null, null);
last = null;
N = 0;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public void enqueue(T t) {
if (this.isEmpty()) {
last = new Node(t, null);
head.next = last;
} else {
Node oldLast = last;
last = new Node(t, null);
oldLast.next = last;
}
N++;
}
public T dequeue() {
if (this.isEmpty()) return null;
Node oldFirst = head.next;
head.next = oldFirst.next;
N--;
//如果队列为空时,要把last置空,如果不置空,last一直会有值
if (this.isEmpty()) last = null;
return oldFirst.item;
}
@Override
public Iterator<T> iterator() {
return new QIterator();
}
private class QIterator implements Iterator<T> {
private Node n = head;
@Override
public boolean hasNext() {
return n.next != null;
}
@Override
public T next() {
Node oldNode = n.next;
n = oldNode;
return oldNode.item;
}
}
private class Node {
T item;
Node next;
public Node(T t, Node next) {
this.item = t;
this.next = next;
}
}
public static void main(String[] args) {
Queue<String> queue = new Queue<>();
queue.enqueue("a");
queue.enqueue("b");
queue.enqueue("c");
queue.enqueue("d");
for (String s : queue) {
System.out.println(s);
}
String dequeue = queue.dequeue();
System.out.println(dequeue);
System.out.println(queue.size());
}
}