算法-第四版-练习1.3.8解答
给定以下输入,给出DoublingStackOfStrings的数组的内容和大小。
it was - the best - of times - - - it was - the - -
DoublingStackOfStirngs,其中添加了返回内部数组大小的方法arraySize()。
/** * Description : * Author : mn@furzoom.com * Date : Sep 29, 2016 9:34:14 AM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch103; import java.util.Iterator; /** * ClassName : DoublingStackOfStrings <br> * Function : TODO ADD FUNCTION. <br> * date : Sep 29, 2016 9:34:14 AM <br> * * @version */ public class DoublingStackOfStrings<Item> implements Iterable<Item> { @SuppressWarnings("unchecked") private Item[] a = (Item[]) new Object[1]; private int n; public int size() { return n; } public boolean isEmpty() { return n == 0; } public void push(Item item) { if (n == a.length) resize(2 * n); a[n++] = item; } public Item pop() { Item item = a[--n]; a[n] = null; if (n > 0 && n == a.length / 4) resize(n * 2); return item; } public int arraySize() { return a.length; } private void resize(int max) { @SuppressWarnings("unchecked") Item[] temp = (Item[]) new Object[max]; for (int i = 0; i < n; i++) temp[i] = a[i]; a = temp; } @Override public Iterator<Item> iterator() { return new ArrayIterator(); } private class ArrayIterator implements Iterator<Item> { private int i = n - 1; @Override public boolean hasNext() { return i >= 0; } @Override public Item next() { return a[i--]; } } }
测试用例:
/** * Description : * Author : mn@furzoom.com * Date : Sep 29, 2016 9:31:46 AM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch103; import edu.princeton.cs.algs4.StdIn; /** * ClassName : E10308 <br> * Function : TODO ADD FUNCTION. <br> * date : Sep 29, 2016 9:31:46 AM <br> * * @version */ public class E10308 { public static void main(String[] args) { DoublingStackOfStrings<String> stack = new DoublingStackOfStrings<String>(); String[] inputs = StdIn.readAllStrings(); for (int i = 0; i < inputs.length; i++) { if (inputs[i].equals("-")) { stack.pop(); } else { stack.push(inputs[i]); } for (String s : stack) { System.out.print(s + " "); } System.out.println(); System.out.println("ArraySize: " + stack.arraySize()); System.out.println(); } } }
结果:
>java -cp ".;../lib/algs4.jar" com .furzoom.lab.algs.ch103.E10308 < com/furzoom/lab/algs/ch103/E10308.txt it ArraySize: 1 was it ArraySize: 2 it ArraySize: 2 the it ArraySize: 2 best the it ArraySize: 4 the it ArraySize: 4 of the it ArraySize: 4 times of the it ArraySize: 4 of the it ArraySize: 4 the it ArraySize: 4 it ArraySize: 2 it it ArraySize: 2 was it it ArraySize: 4 it it ArraySize: 4 the it it ArraySize: 4 it it ArraySize: 4 it ArraySize: 2数据文件E10308.txt
it was - the best - of times - - - it was - the - -
作者:马 岩(Furzoom) (http://www.cnblogs.com/furzoom/)
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。
版权声明:本文的版权归作者与博客园共同所有。转载时请在明显地方注明本文的详细链接,未经作者同意请不要删除此段声明,感谢您为保护知识产权做出的贡献。