队列

队列的特色:

队列是一种特殊的线性结构,它只容许在队列的首部(head)进行删除操做,这称为“出队”,而在队列的尾部(tail)进行插入操做,这称为“入队”,当队列中没有元素时(即head=tail),称为空队列。
队列将是咱们从此学习广搜以及队列优化(Bellman-Ford)最短路算法的核心数据结构。
代码以下:java

import java.util.LinkedList;
import java.util.Queue;
public class D队列 {

	public static void main(String[] args) {
		
		        Queue<Integer> queue = new LinkedList<>();//建立队列
		        queue.offer(1);//如下是添加元素进对列
		        queue.offer(2);
		        queue.offer(3);
		        queue.offer(4);
		        for(int e : queue) {//遍历输出,定义一个变量e遍历队列输出
		            System.out.println(e);//1 2 3 4 
		        }
		        System.out.println("**********");
		        System.out.println("poll : " + queue.poll());//1,poll取出并删除队头的元素
		        System.out.println("----------");

		        for(int e : queue) {
		            System.out.println(e); //2 3 4 
		        }
		        System.out.println("elemet is: " + queue.element());//2
		        System.out.println("----------");

		        for(int e : queue) {
		            System.out.println(e);//2 3 4 
		        }

		        System.out.println("peek : " + queue.peek());//2
		        System.out.println("**********");

		        for(int e : queue) {
		            System.out.println(e);//2 3 4
		        }
	}
}

1.Java中队列的建立以及头文件算法

Queue<Integer> queue = new LinkedList<>();

头文件:
import java.util.LinkedList;
import java.util.Queue;

2.关于队列的“出入”数据结构

往队列中添加元素:add(若是队列已经满,则抛出异常);
                put( 若是已经满了,则等待它为空或者抛出异常);
                offer(已满,返回false);
从队列中取出或者删除元素:
                remove(直接删除队头的元素);
                peek(直接取出队头元素并不删除);
                element(对peek方法进行简单封装,若是队头元素存在则取出,不存在则抛出异常);
                poll(取出并删除队头的元素,当队列为空则返回null);
                take(取出并删除队头元素,为空则等待或者抛出异常);
offer()方法通常与pool()方法相对应;
put方法通常与take(方法相对应);

3.对上述代码的分解
(1).poll()学习

System.out.println("poll : " + queue.poll());//1,poll取出并删除队头的元素

(2).element()优化

System.out.println("elemet is: " + queue.element());//2由于上一个已经删除了队头元素1,因此此时队头元素是2,直接取出。

(3).peek()code

System.out.println("peek : " + queue.peek());//2直接取出并不删除
相关文章
相关标签/搜索