算法Sedgewick第四版-第1章基础-018一解决不能声明泛型数组的两咱方法(强转或反射)
1.
/******************************************************************************
* Compilation: javac ResizingArrayStackWithReflection.java
* Execution: java ResizingArrayStackWithReflection < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* Stack implementation with a resizing array.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java ResizingArrayStackWithReflection < tobe.txt
* to be not that or be (2 left on stack)
*
* Written by Bruno Lehouque.
*
******************************************************************************/ import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.NoSuchElementException; /**
* A LIFO Stack using a resizeable array.
*/
public class ResizingArrayStackWithReflection<Item> implements Iterable<Item> { private Class<Item[]> itemArrayClass;
private Item[] array;
private int N = 0; public ResizingArrayStackWithReflection(Class<Item[]> itemArrayClass) {
this.itemArrayClass = itemArrayClass;
array = itemArrayClass.cast(Array.newInstance(itemArrayClass.getComponentType(), 1));
} /**
* Adds a non-{@code null} element on top of the Stack.
*
* @param item
* the element which is to be added to the Stack
*
* @throws IllegalArgumentException if {@code item} is {@code null}.
*/
public void push(Item item) {
if (item == null)
throw new IllegalArgumentException("Cannot add null item.");
if (N == array.length)
resize(array.length * 2);
array[N++] = item;
} /**
* Removes and returns the top element of the Stack.
*
* @return the top element of the Stack
*
* @throws NoSuchElementException if the Stack is empty
*/
public Item pop() {
if (isEmpty())
throw new NoSuchElementException();
Item item = array[--N];
array[N] = null;
if ((N > 0) && (N <= array.length / 4))
resize(array.length / 2);
return item;
} /**
* Returns, but doesn't remove, the top element of the Stack.
*
* @return the top element of the Stack
*
* @throws NoSuchElementException if the Stack is empty
*/
public Item peek() {
if (isEmpty())
throw new NoSuchElementException();
return array[N - 1];
} /**
* Returns {@code true} if the Stack is empty.
*
* @return {@code true} if the Stack is empty
*/
public boolean isEmpty() {
return N == 0;
} /**
* Returns the size of the Stack.
*
* @return the size of the Stack
*/
public int size() {
return N;
} /**
* Returns an iterator which iterates over the Stack from the top element
* to the bottom element.
*
* @return an iterator which iterates over the Stack from the top element
* to the bottom element
*/
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
} private void resize(int size) {
Item[] newarray = itemArrayClass.cast(Array.newInstance(itemArrayClass.getComponentType(), size));
for (int i = 0; i < N; i++)
newarray[i] = array[i];
array = newarray;
} private class ReverseArrayIterator implements Iterator<Item> { private int i = N-1; @Override
public boolean hasNext() {
return i >= 0;
} @Override
public Item next() {
if (!hasNext())
throw new NoSuchElementException();
return array[i--];
} @Override
public void remove() {
throw new UnsupportedOperationException("Not supported.");
} } /**
* Test client (copied from ResizingArrayStack).
*/
public static void main(String[] args) {
ResizingArrayStackWithReflection<String> s = new ResizingArrayStackWithReflection<String>(String[].class);
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) s.push(item);
else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
}
StdOut.println("(" + s.size() + " left on stack)");
}
}
2.
/******************************************************************************
* Compilation: javac ResizingArrayStack.java
* Execution: java ResizingArrayStack < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* Stack implementation with a resizing array.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java ResizingArrayStack < tobe.txt
* to be not that or be (2 left on stack)
*
******************************************************************************/ import java.util.Iterator;
import java.util.NoSuchElementException; /**
* The <tt>ResizingArrayStack</tt> class represents a last-in-first-out (LIFO) stack
* of generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a resizing array, which double the underlying array
* when it is full and halves the underlying array when it is one-quarter full.
* The <em>push</em> and <em>pop</em> operations take constant amortized time.
* The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
* constant time in the worst case.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class ResizingArrayStack<Item> implements Iterable<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack /**
* Initializes an empty stack.
*/
public ResizingArrayStack() {
a = (Item[]) new Object[2];
N = 0;
} /**
* Is this stack empty?
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return N == 0;
} /**
* Returns the number of items in the stack.
* @return the number of items in the stack
*/
public int size() {
return N;
} // resize the underlying array holding the elements
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
} /**
* Adds the item to this stack.
* @param item the item to add
*/
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
} /**
* Removes and returns the item most recently added to this stack.
* @return the item most recently added
* @throws java.util.NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4) resize(a.length/2);
return item;
} /**
* Returns (but does not remove) the item most recently added to this stack.
* @return the item most recently added to this stack
* @throws java.util.NoSuchElementException if this stack is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return a[N-1];
} /**
* Returns an iterator to this stack that iterates through the items in LIFO order.
* @return an iterator to this stack that iterates through the items in LIFO order.
*/
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
} // an iterator, doesn't implement remove() since it's optional
private class ReverseArrayIterator implements Iterator<Item> {
private int i; public ReverseArrayIterator() {
i = N-1;
} public boolean hasNext() {
return i >= 0;
} public void remove() {
throw new UnsupportedOperationException();
} public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i--];
}
} /**
* Unit tests the <tt>Stack</tt> data type.
*/
public static void main(String[] args) {
ResizingArrayStack<String> s = new ResizingArrayStack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) s.push(item);
else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
}
StdOut.println("(" + s.size() + " left on stack)");
}
}
算法Sedgewick第四版-第1章基础-018一解决不能声明泛型数组的两咱方法(强转或反射)的更多相关文章
- 算法Sedgewick第四版-第1章基础-001递归
一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)
一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)
一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-006归并排序(Mergesort)
一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursivel ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版
package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)
一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)
一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...
- 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的
1. package algorithms.stacks13; /******************************************************************* ...
- 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法
1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...
随机推荐
- 使用Innobackupex快速搭建(修复)MySQL主从架构
MySQL的主从搭建大家有很多种方式,传统的mysqldump方式是很多人的选择之一.但对于较大的数据库则该方式并非理想的选择.使用Xtrabackup可以快速轻松的构建或修复mysql主从架构.本文 ...
- 织梦dedecms如何批量替换文章内容和缩略图
文章来自:http://blog.sina.com.cn/s/blog_475ea1130101co6w.html 第一种方法: 进入后台,点左侧的采集,点选批量维护的数据库内容替换. 1.替换标题内 ...
- ACM学习历程—SNNUOJ1213 加油站问题(动态规划 || 数学)
题目链接:http://219.244.176.199/JudgeOnline/problem.php?id=1213 这是这次微软实习面试的一道题,当时只相出了一个2n的做法,面试官让我优化成n的做 ...
- BZOJ4066:简单题
浅谈\(K-D\) \(Tree\):https://www.cnblogs.com/AKMer/p/10387266.html 题目传送门:https://lydsy.com/JudgeOnline ...
- 存储过程错误异常处理例子 --> DECLARE EXIT HANDLER FOR SQLEXCEPTION (转)
刚才一个朋友问到: mysql 有类似 mssql 退出执行的方法不? 比如我执行到某个条件,下面就终止执行了. 想起以前写的存储过程,找了好久才找到,就发给他,希望对他有所帮助,贴在这里,留作 ...
- 除了IE浏览器能识别之外,其他浏览器都不能识别的html写法
最近写html页面的时候发现顶部边界margin-top用了定位之后,IE的跟其他浏览器不同,所以用到了把IE跟其他浏览器区分开来的写法 <!--[if !IE]> <div cla ...
- TX2上安装spi和uart驱动
替换/boot目录下的Image文件 重新烧写dtb文件.烧写方式参考. 文件下载
- (转)nodejs搭建本地http服务器
本文转载自:http://www.cnblogs.com/shawn-xie/archive/2013/06/06/3121173.html 由于不做php相关的东西,懒得装apache,干脆利用no ...
- 第十课 go语言函数
1 内置函数 len() 函数可以接受不同类型参数并返回该类型的长度. 如果我们传入的是字符串则返回字符串的长度, 如果传入的是数组,则返回数组中包含的元素个数. 2 自定义函数 // 函数返回单个 ...
- mybatis 学习二 MyBatis简介与配置MyBatis+Spring+MySql
1.2.2建立MySql数据库 在C:\Program Files\MySQL\MySQL Server 5.7\bin下面: 首先连接MySQL: mysql -u root -p ...