前言
为了面试,时隔一年不得不重新复习数据结构与算法,这次重新复习很有收获,以前在上课总有不清晰的知识,通过这次手写一遍和敲一遍代码,以前不清晰的知识都变得清晰了,果然学编程还是得多敲代码,多敲代码,多敲代码,也要多总结,多总结,多总结。
学习资源
视频 黑马程序员 数据结构与算法
队列
队列是一种基于先进先出(FIFO)的数据结构,是一种只能在一端进行插入,在另一端进行删除操作的特殊线性表,它按照先进先出的原则存储数据,先进入的数据,在读取数据时先读被读出来。
import java.util.Iterator;
//队列
public class Queue<T> implements Iterable<T> {
private Node head; //记录首结点
private Node last; //记录最后一个结点
private int N; //记录队列中元素的个数
//节点类
private class Node{
public T item;
public Node next;
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
}
//初始化
public Queue(){
this.head = new Node(null,null);
this.last = null;
this.N = 0;
}
//判断队列是否为空
public boolean isEmpty(){
return N==0;
}
//返回队列中元素的个数
public int size(){
return N;
}
//向队列中插入元素t 入队 从尾结点入队
public void enqueue(T t){
//空队列 头结点和尾结点都指向null
if(last==null){
last = new Node(t,null); //元素t成为尾结点的值
head.next = last; //头结点指向尾结点
}else{
//当前尾结点last不为null
Node oldLast = last;
last = new Node(t,null); //元素t成为尾结点的值
oldLast.next = last; //旧尾结点指向新尾结点
}
//元素个数+1
N++;
}
//从队列中拿出一个元素 出队 从头结点出队
public T dequeue(){
if(isEmpty()){ //元素个数为 0
return null;
}
Node oldFirst = head.next;
head.next = oldFirst.next; //删除第一个元素
N--;
//因为出队列其实是在删除元素,因此如果队列中的元素被删除完了,需要重置last=null;
if (isEmpty()){
last=null;
}
return oldFirst.item;
}
//重写迭代器遍历方法
//实现Iterable接口,重写接口的iterator方法;
@Override
public Iterator<T> iterator() {
return new QIterator();
}
//实现Iterator接口,重写hasNext方法和next方法;
private class QIterator implements Iterator<T>{
private Node n;
public QIterator(){
this.n=head;
}
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public T next() {
n = n.next;
return n.item;
}
}
//测试
public static void main(String[] args) {
//创建队列对象
Queue<String> q = new Queue<>();
//测试队列的enqueue方法
q.enqueue("a");
q.enqueue("b");
q.enqueue("c");
q.enqueue("d");
for (String str : q) {
System.out.println(str);
}
System.out.println("-------------------------------");
//测试队列的dequeue方法
String result = q.dequeue();
System.out.println("出队列的元素是:"+result);
System.out.println("剩余的元素个数:"+q.size());
}
}