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一解决不能声明泛型数组的两咱方法(强转或反射)的更多相关文章

  1. 算法Sedgewick第四版-第1章基础-001递归

    一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...

  2. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)

    一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...

  3. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)

    一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...

  4. 算法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 ...

  5. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版

    package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...

  6. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)

    一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...

  7. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)

    一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...

  8. 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的

    1. package algorithms.stacks13; /******************************************************************* ...

  9. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法

    1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...

随机推荐

  1. Codeforces Round #254(div2)B

    就是看无向图有几个连通块,答案就是2n-num. 范围很小,就用矩阵来存图减少代码量. #include<iostream> #include<cstdio> #include ...

  2. CodeForces - 651D:Image Preview (双指针&)

    Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed ...

  3. 修改git commit 最后一次提交的注释信息 以及如何退出git bash vim编辑器

    https://www.cnblogs.com/sandy-happyhour/p/5950084.html 今天用git commit -m “注释”提交的时候,注释写错了,于是各种查资料开始了和g ...

  4. 使用自定义端口连接SQL Server 2008的方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. 使用过SQL Server的人大多都知道,SQL Server服务器默认监听的端口号是1433,但是我今天遇到的问题是我的机器上有三个数据库实例, ...

  5. 【全面解禁!真正的Expression Blend实战开发技巧】第六章 认识ListBox

    反反复复考虑后,准备把这一章的切入点瞄准ListBox.并用了一个看起来有点别扭的标题“认识ListBox",许多人看到这里就不爱看了,即使是大学里用winform的学生也会说ListBox ...

  6. 释放Windows C盘空间 -- 虚拟内存和休眠文件

    本文由Suzzz原创,发布于 http://www.cnblogs.com/Suzzz/p/4111718.html ,转载请保留此声明. 项目组有一Windows工作站, 由于需要使用Kinect最 ...

  7. 12.Selenium+Python案例 -- 今日头条(获取科技栏目的所有新闻标题)

    一:具体代码实现 # -*- coding: utf-8 -*-# @Time : 2018/7/26 16:33# @Author : Nancy# @Email : NancyWangDL@163 ...

  8. Mysql事件的创建和使用

    1.查看事件是否开启SHOW VARIABLES LIKE 'event_scheduler'; 2.开启事件SET GLOBAL event_scheduler = ON; 3.创建事件DELIMI ...

  9. FMDB是iOS平台的SQLite数据库框架

    1.FMDB简介 什么是FMDBFMDB是iOS平台的SQLite数据库框架 FMDB以OC的方式封装了SQLite的C语言API 为什么使用FMDB使用起来更加面向对象,省去了很多麻烦.冗余的C语言 ...

  10. Day2-VIM(三):删除

    字符删除 x 删除光标所在处字符 X 删除光标所在前字符 这里没有什么可注意的地方,但需要说明一下的是 通常情况下,新手一旦着急便会按着x不动,从而达到删除一大块文本的目的 如果是头几天使用还好说,但 ...