java中的队(Queue)和栈(Stack)

来源:互联网 发布:vb post教程 编辑:程序博客网 时间:2024/05/01 20:14

  看着编程思想第四版,爽的是里面的程序,当你理解到这个程序的牛逼之处时,就是你拍板叫好的那一刻,终于连追带赶看到了第十一章持有对象,被这扫描版伤透了眼。写完这个笔记,眼保健操是个好主意。

【队和栈特点实验】

package com.jay.knowledge.queue_study;import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList;import java.util.Queue;import java.util.Stack;/** * @function: Queue的学习(对列,对,就是队列)  典型的先进先出的容器(传送带似) * @author:Jay * @date:2013-12-5 */public class Queue001 {public static void main(String[] args) {//queue不支持ArrayList,如下会报错//Queue<String> queue = new ArrayList<String>();//queue支持LinkedList/*Queue<String> queue = new LinkedList<String>();queue.add("one");queue.add("two");queue.add("three");queue.add("four");queue.add("five");queue.add("six");Iterator<String> iterator = queue.iterator();while (iterator.hasNext()) {String q = (String) iterator.next();//先进先出System.out.print("   "+q);}*/Queue<String> queue = new LinkedList<String>();queue.offer("one");queue.offer("two");queue.offer("three");queue.offer("four");queue.offer("five");queue.offer("six");System.out.println("------进队顺序------------");System.out.println("one two three four five six");System.out.println("------出队顺序------------");//,poll删除并移动指针,peek()查询System.out.print("  "+queue.poll());System.out.print("  "+queue.poll());System.out.print("  "+queue.poll());System.out.print("  "+queue.poll());System.out.print("  "+queue.poll());System.out.print("  "+queue.poll());System.out.println();//比较先进后出的StackStack<String> stack = new Stack<String>();//进栈stack.push("one");stack.push("two");stack.push("three");stack.push("four");stack.push("five");stack.push("six");System.out.println("------进栈顺序------------");System.out.println("one two three four five six");System.out.println("------出栈顺序------------");//出栈pop删除并移动指针,peek()只拿出最后进栈的值System.out.print("  "+stack.pop());System.out.print("  "+stack.pop());System.out.print("  "+stack.pop());System.out.print("  "+stack.pop());System.out.print("  "+stack.pop());System.out.print("  "+stack.pop());}}


【运行结果】

------进队顺序------------
one two three four five six
------出队顺序------------
  one  two  three  four  five  six
------进栈顺序------------
one two three four five six
------出栈顺序------------
  six  five  four  three  two  one
【方法说明】

1.栈(Stack):

①peek():只取出栈顶值,但不会对栈进行操作,如果不断去做操作,最后的得到的值是相同,此值是最后进去的值。

②push(T):向栈中添加值。

③pop():出栈,并操作栈,取出后进去的值,并删除,然后移动指针。

2.队列(Queue)

①peek():只取出队列中的值,不会对栈进行操作,如果不断去做操作,最后的得到的值是相同,此值是最先进去的值。

②offer(T):向队列中添加值。

③poll():出队列,并操作队列,取出先进队列的值,并删除,然后移动指针。