Java队列和栈(Queue和Deque)

队列Queue

队列Queue也是Collection的一个子接口

    队列接口,底层是一个特殊的线性表。从一端添加元素(offer),从另一端取出元素(pop)

    遵循原则:FIFO(first input,first output)先进先出原则

    因为队列要经常进行增删操作。因此使用LinkedList链表来实现Queue接口更合适效率更高,而不是ArrayList

常用API

    boolean add(E e)    从队尾追加元素

    boolean offer(E e)    从队尾追加元素

    E poll()    返回并移除队首元素

    E peek()    查看队首元素

    boolean isEmpty()    查看队列是否为空

    E remove()    移除队首并返回

    E remove(E e)    移除队列中指定的元素(不常用)

Deque 双端队列

两端都可进可出(实现类为LinkedList,因为要经常进行增删操作,所以用链表)
常用API
大部分方法和上面一样,但还是会有些不同的
boolean off(E e) 默认从队尾插入元素
boolean offLast(E e)/offFirst(E e) 从队尾/首插入元素
E poll() 默认移除队首
E pollFirst()/pollLast() 移除对首/尾元素
E peek() 查看队首元素
常用API
大部分方法和上面一样,但还是会有些不同的
boolean off(E e) 默认从队尾插入元素
boolean offLast(E e)/offFirst(E e) 从队尾/首插入元素
E poll() 默认移除队首
E pollFirst()/pollLast() 移除对首/尾元素
E peek() 查看队首元素

E peekFirst()/peekLast() 查看队首/队尾元素

    练习代码:

public static void main(String[] args) {
		Deque<String> deque = new LinkedList<String>();
		deque.offer("A");
		deque.offerFirst("B");
		System.out.println(deque);
		deque.offerLast("C");
		System.out.println(deque);
		deque.offer("D");
		deque.offer("E");
		deque.offer("F");
		/*
		 * poll()出双端队列
		 */
		System.out.println("移除队首:"+deque.poll());
		System.out.println(deque);
		System.out.println("首:"+deque.pollFirst());
		System.out.println("尾:"+deque.pollLast());
		System.out.println(deque);
		/*
		 * peek()查看队首元素
		 */
		System.out.println(deque.peek());
	}

当我们限制双端队列的一端不能进行任何操作时(人为规定的),即为桟Stack,进出原则:FILO(first input,last output)先进后出
为了更加形象的表示桟,通常不调用offer和poll用如下两个方法:
boolean push() 按照桟的模式,从队首开始添加元素
E pop() 取出队首元素

我们如果要是把双端队列限制为桟的话,就要按照桟的规定,只能从一端进行进出,在中间及另一端则不能进行操作

        /*
	 *桟:进出原则:先进后出
	 *	将双端队列的一端进行限制:严谨进出操作(认为限制) 
	 */
	public static void main(String[] args) {
		
		Deque<String> stack = new LinkedList<String>(); 
		/*
		 * 为了更加形象的表示桟
		 * 通常不调用offer和poll
		 * 
		 * 使用push表示进桟
		 * 使用pop表示出桟
		 */
		stack.push("A");
		stack.push("B");
		stack.push("C");
		/*
		 * 当使用桟结构时,toString返回值为出桟顺序
		 */
		System.out.println(stack);
		System.out.println(stack.pop());
		System.out.println(stack);
	}	

猜你喜欢

转载自blog.csdn.net/woainiqazwsx123/article/details/80794068
今日推荐