算法-第四版-练习1.3.14解答
问题
编写一个类ResizingArrayQueueOfStrings,使用定长数组实现队列的抽象,然后扩展实现,使用调整数组的方法突破大小的限制。
解决思路
参照堆栈的实现即可。
代码
/** * Description : * Author : mn@furzoom.com * Date : Oct 20, 2016 3:15:52 PM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch103; /** * ClassName : ResizingArrayQueueOfStrings <br> * Function : TODO ADD FUNCTION. <br> * date : Oct 20, 2016 3:15:52 PM <br> * * @version */ public class ResizingArrayQueueOfStrings { private int first; private int last; private int count; private String[] queue; public ResizingArrayQueueOfStrings() { first = 0; last = 0; count = 1; queue = new String[count]; } public boolean isEmpty() { return first == last; } public int size() { return last - first; } public void enqueue(String s) { if (last == count) { resizing(2 * size()); } queue[last++] = s; } public String dequeue() { if (size() < count / 4) { resizing(2 * size()); } return queue[first++]; } private void resizing(int n) { String[] tmp = new String[n]; int j = 0; for (int i = first; i < last; i++) { tmp[j++] = queue[i]; } queue = tmp; count = n; last = last - first; first = 0; } public static void main(String[] args) { ResizingArrayQueueOfStrings queue = new ResizingArrayQueueOfStrings(); queue.enqueue("a"); System.out.println("size(): " + queue.size() + " | count: " + queue.count); queue.enqueue("b"); System.out.println("size(): " + queue.size() + " | count: " + queue.count); queue.enqueue("c"); System.out.println("size(): " + queue.size() + " | count: " + queue.count); queue.enqueue("d"); System.out.println("size(): " + queue.size() + " | count: " + queue.count); queue.enqueue("e"); System.out.println("size(): " + queue.size() + " | count: " + queue.count); queue.enqueue("f"); System.out.println("size(): " + queue.size() + " | count: " + queue.count); queue.enqueue("g"); while (!queue.isEmpty()) { System.out.println(queue.dequeue() + " | size(): " + queue.size() + " | count: " + queue.count); } } }
输出:
size(): 1 | count: 1 size(): 2 | count: 2 size(): 3 | count: 4 size(): 4 | count: 4 size(): 5 | count: 8 size(): 6 | count: 8 a | size(): 6 | count: 8 b | size(): 5 | count: 8 c | size(): 4 | count: 8 d | size(): 3 | count: 8 e | size(): 2 | count: 8 f | size(): 1 | count: 8 g | size(): 0 | count: 2
作者:马 岩(Furzoom) (http://www.cnblogs.com/furzoom/)
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。