算法Sedgewick第四版-第1章基础-008一用数组实现栈(泛型、可变大小)
package algorithms.ADT; /******************************************************************************
* Compilation: javac FixedCapacityStackOfStrings.java
* Execution: java FixedCapacityStackOfStrings
* Dependencies: StdIn.java StdOut.java
*
* Stack of strings implementation with a fixed-size array.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java FixedCapacityStackOfStrings 5 < tobe.txt
* to be not that or be
*
* Remark: bare-bones implementation. Does not do repeated
* doubling or null out empty array entries to avoid loitering.
*
******************************************************************************/ import java.util.Iterator;
import java.util.NoSuchElementException; import algorithms.util.StdIn;
import algorithms.util.StdOut; public class FixedCapacityStackOfStrings implements Iterable<String> {
private String[] a; // holds the items
private int N; // number of items in stack // create an empty stack with given capacity
public FixedCapacityStackOfStrings(int capacity) {
a = new String[capacity];
N = 0;
} public boolean isEmpty() { return N == 0; }
public boolean isFull() { return N == a.length; }
public void push(String item) { a[N++] = item; }
public String pop() { return a[--N]; }
public String peek() { return a[N-1]; }
public Iterator<String> iterator() { return new ReverseArrayIterator(); } public class ReverseArrayIterator implements Iterator<String> {
private int i = N-1; public boolean hasNext() {
return i >= 0;
} public String next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i--];
} public void remove() {
throw new UnsupportedOperationException();
}
} public static void main(String[] args) {
int max = Integer.parseInt(args[0]);
FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) stack.push(item);
else if (stack.isEmpty()) StdOut.println("BAD INPUT");
else StdOut.print(stack.pop() + " ");
}
StdOut.println(); // print what's left on the stack
StdOut.print("Left on stack: ");
for (String s : stack) {
StdOut.print(s + " ");
}
StdOut.println();
}
}
用泛型的
package algorithms.ADT; /******************************************************************************
* Compilation: javac FixedCapacityStack.java
* Execution: java FixedCapacityStack
* Dependencies: StdIn.java StdOut.java
*
* Generic stack implementation with a fixed-size array.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java FixedCapacityStack 5 < tobe.txt
* to be not that or be
*
* Remark: bare-bones implementation. Does not do repeated
* doubling or null out empty array entries to avoid loitering.
*
******************************************************************************/ import java.util.Iterator;
import java.util.NoSuchElementException; import algorithms.util.StdIn;
import algorithms.util.StdOut; public class FixedCapacityStack<Item> implements Iterable<Item> {
private Item[] a; // holds the items
private int N; // number of items in stack // create an empty stack with given capacity
public FixedCapacityStack(int capacity) {
a = (Item[]) new Object[capacity]; // no generic array creation
N = 0;
} public boolean isEmpty() { return N == 0; }
public void push(Item item) { a[N++] = item; }
public Item pop() { return a[--N]; }
public Iterator<Item> iterator() { return new ReverseArrayIterator(); } public class ReverseArrayIterator implements Iterator<Item> {
private int i = N-1; public boolean hasNext() {
return i >= 0;
} public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i--];
} public void remove() {
throw new UnsupportedOperationException();
}
} public static void main(String[] args) {
int max = Integer.parseInt(args[0]);
FixedCapacityStack<String> stack = new FixedCapacityStack<String>(max);
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) stack.push(item);
else if (stack.isEmpty()) StdOut.println("BAD INPUT");
else StdOut.print(stack.pop() + " ");
}
StdOut.println(); // print what's left on the stack
StdOut.print("Left on stack: ");
for (String s : stack) {
StdOut.print(s + " ");
}
StdOut.println();
}
}
可变大小的
package algorithms.ADT; /******************************************************************************
* 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; import algorithms.util.StdIn;
import algorithms.util.StdOut; /**
* 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章基础-008一用数组实现栈(泛型、可变大小)的更多相关文章
- 算法Sedgewick第四版-第1章基础-007一用两个栈实现简单的编译器
1. package algorithms.util; import algorithms.ADT.Stack; /****************************************** ...
- 算法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; /******************************************************************* ...
随机推荐
- JavaScript如何处理解析JSON数据详解
JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧. JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON ...
- const、define与sizeof
一.const的用途 1.定义const常量 2.可以修饰函数的形参,返回值,以及函数体.被const修饰的内容可以受到强制保护,防止被意外修改,提高程序健壮性. const 返回值 函数返回值为 c ...
- nodejs读取excel内容批量替换并生成新的html和新excel对照文件
因为广告投放需要做一批对外投放下载页面,由于没有专门负责填充页面的编辑同学做,只能前端来做了, 拿到excel看了一下,需要生成200多个文件,一下子懵逼了. 这要是来回复制粘贴太low了 正好最新用 ...
- 学习动态性能表(22)V$resource_limit
学习动态性能表 第20篇--V$resource_limit 2007.6.15 就一条SQL语句供你参考: select * from V$RESOURCE_LIMIT where resourc ...
- SOA、微服务与服务网格
SOA架构解析 SOA 全称是: Service Oriented Architecture,中文释义为 “面向服务的架构”,它是一种设计理念,其中包含多个服务, 服务之间通过相互依赖最终提供一系列完 ...
- 从内存中直接运行PE程序
效果是这样的,假设一个PE数据在内存里面了,我们利用下面我讲的技术可以直接建立一个进程并运行这个PE,当然直接在本进程运行在可以,这两钟技术在前些时日我都有实现,今天我只说关于建立进程并运行的,当然, ...
- QString的拼接
QString的append()函数则提供了类似的操作,例如: 1. str = "User: "; 2. str.append(userName); 3. str ...
- C/C++变量命名规则,个人习惯总结【转载】
C_C++变量命名规则 原文地址:http://blog.sina.com.cn/s/blog_8a7012cf01017h9p.html 变量命名规则是为了增强代码的可读性和容易维护性.以下为C++ ...
- 第一章计算机网络和因特网-day02
1.互联网中的时延:处理时延.排队时延.传输时延.传播时延. 处理时延:检查分组首部和决定该分组导向何处的时间. 排队时延:分组在链路上等待传输的时延. 传输时延:分组经过路由器与交换机的过程的时延. ...
- mysql 备份语句
模板: mysqldump -h IP -u user -p 选项 dbname>d:\db.sql 选项:-f表示有错误时继续 -d 表示--no-create-db, -n表示--no-da ...