【Java】栈和队列

来源:互联网 发布:linux vi如何退出 编辑:程序博客网 时间:2024/06/14 10:34
public class QueueAndStack {private static final long LEVEL = 20150701;//码讲版本/** * 队列的基本操作 */public void testQueue() {Queue<String> queue = new LinkedList<String>();System.out.println("向队尾添加元素:"+queue.offer("one"));queue.offer("two");queue.offer("three");queue.offer("four");System.out.println("全部队列:" + queue);System.out.println("出队操作:" + queue.poll());System.out.println("取出后全部队列:" + queue);System.out.println("查询队尾元素,不出队:"+queue.peek());System.out.println("查询后全部队列:" + queue);System.out.println("当前队列元素个数:"+queue.size());//队列的遍历 while方式并做出队操作while(queue.size()>0){System.out.println("遍历:"+queue.poll());}System.out.println("While遍历后队列:"+queue);//迭代器遍历,不会做出队操作System.out.println("向队尾添加元素:"+queue.offer("one"));queue.offer("two");queue.offer("three");queue.offer("four");for(String q:queue){System.out.println("遍历:"+q);}System.out.println("迭代遍历后队列:"+queue);}/** * 栈的基本操作 */@Testpublic void testStack(){Deque<String> stack = new LinkedList<String>();stack.push("one");stack.push("two");stack.push("three");stack.push("four");System.out.println("查看栈顶元素:"+stack.peek());System.out.println("出栈:"+stack.pop());System.out.println("查看栈顶元素:"+stack.peek());System.out.println("栈大小:"+stack.size());//迭代遍历for(String q:stack){System.out.println("遍历:"+q);}System.out.println("迭代遍历后队列:"+stack);//出栈遍历while(stack.size()>0){System.out.println("出栈遍历:"+stack.pop());}System.out.println("栈大小:"+stack.size());}}

0 0