算法-第四版-练习1.3.6解答
下面这段代码对队列q进行了什么操作?
Stack<String> stack = new Stack<String>(); while (!q.isEmpty()) stack.push(q.dequeue()); while (!stack.isEmpty()) q.enqueue(stack.pop());
显然,将队列中的元素进行了逆序。
/** * Description : * Author : mn@furzoom.com * Date : Sep 28, 2016 10:21:54 AM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch103; import java.util.Iterator; import edu.princeton.cs.algs4.StdIn; /** * ClassName : Queue <br> * Function : TODO ADD FUNCTION. <br> * date : Sep 28, 2016 10:21:54 AM <br> * * @version */ public class Queue<Item> implements Iterable<Item> { private Node first; private Node last; private int n; private class Node { Item item; Node next; } public boolean isEmpty() { return first == null; } public int size() { return n; } public void enqueue(Item item) { Node oldlast = last; last = new Node(); last.item = item; last.next = null; if (isEmpty()) { first = last; } else { oldlast.next = last; } n++; } public Item dequeue() { Item item = first.item; first = first.next; if (isEmpty()) { last = null; } n--; return item; } @Override public Iterator<Item> iterator() { return new QueueIterator(); } private class QueueIterator implements Iterator<Item> { private Node current = first; @Override public boolean hasNext() { return current != null; } @Override public Item next() { Item item = current.item; current = current.next; return item; } } }
测试代码:
/** * Description : * Author : mn@furzoom.com * Date : Sep 28, 2016 4:20:38 PM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch103; /** * ClassName : E10306 <br> * Function : TODO ADD FUNCTION. <br> * date : Sep 28, 2016 4:20:38 PM <br> * * @version */ public class E10306 { public static void test(Queue<String> q) { Stack<String> stack = new Stack<String>(); while (!q.isEmpty()) stack.push(q.dequeue()); while (!stack.isEmpty()) q.enqueue(stack.pop()); } public static void main(String[] args) { Queue<String> q = new Queue<String>(); q.enqueue("a"); q.enqueue("b"); q.enqueue("c"); q.enqueue("d"); for (String s : q) System.out.print(s + " "); System.out.println(); test(q); for (String s : q) System.out.print(s + " "); System.out.println(); } }
结果如下:
a b c d d c b a
作者:马 岩(Furzoom) (http://www.cnblogs.com/furzoom/)
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。