1.

package algorithms.stacks13;

/******************************************************************************
* Compilation: javac ResizingArrayBag.java
* Execution: java ResizingArrayBag
* Dependencies: StdIn.java StdOut.java
*
* Bag implementation with a resizing array.
*
******************************************************************************/ import java.util.Iterator;
import java.util.NoSuchElementException; import algorithms.util.StdOut; /**
* The <tt>ResizingArrayBag</tt> class represents a bag (or multiset) of
* generic items. It supports insertion and iterating over the
* items in arbitrary order.
* <p>
* This implementation uses a resizing array.
* See {@link LinkedBag} for a version that uses a singly-linked list.
* The <em>add</em> operation takes constant amortized time; the
* <em>isEmpty</em>, and <em>size</em> operations
* take constant time. Iteration takes time proportional to the number of items.
* <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 ResizingArrayBag<Item> implements Iterable<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack /**
* Initializes an empty bag.
*/
public ResizingArrayBag() {
a = (Item[]) new Object[2];
N = 0;
} /**
* Is this bag empty?
* @return true if this bag is empty; false otherwise
*/
public boolean isEmpty() {
return N == 0;
} /**
* Returns the number of items in this bag.
* @return the number of items in this bag
*/
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 bag.
* @param item the item to add to this bag
*/
public void add(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
} /**
* Returns an iterator that iterates over the items in the bag in arbitrary order.
* @return an iterator that iterates over the items in the bag in arbitrary order
*/
public Iterator<Item> iterator() {
return new ArrayIterator();
} // an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
public boolean hasNext() { return i < N; }
public void remove() { throw new UnsupportedOperationException(); } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i++];
}
} /**
* Unit tests the <tt>ResizingArrayBag</tt> data type.
*/
public static void main(String[] args) {
ResizingArrayBag<String> bag = new ResizingArrayBag<String>();
bag.add("Hello");
bag.add("World");
bag.add("how");
bag.add("are");
bag.add("you"); for (String s : bag)
StdOut.println(s);
} }

2.

 package algorithms.stacks13;

 /******************************************************************************
* Compilation: javac ResizingArrayQueue.java
* Execution: java ResizingArrayQueue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* Queue implementation with a resizing array.
*
* % java ResizingArrayQueue < tobe.txt
* to be or not to be (2 left on queue)
*
******************************************************************************/ import java.util.Iterator;
import java.util.NoSuchElementException; import algorithms.util.StdIn;
import algorithms.util.StdOut; /**
* The <tt>ResizingArrayQueue</tt> class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO 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>enqueue</em> and <em>dequeue</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 ResizingArrayQueue<Item> implements Iterable<Item> {
private Item[] q; // queue elements
private int N; // number of elements on queue
private int first; // index of first element of queue
private int last; // index of next available slot /**
* Initializes an empty queue.
*/
public ResizingArrayQueue() {
q = (Item[]) new Object[2];
N = 0;
first = 0;
last = 0;
} /**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {
return N == 0;
} /**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {
return N;
} // resize the underlying array
private void resize(int max) {
assert max >= N;
Item[] temp = (Item[]) new Object[max];
for (int i = 0; i < N; i++) {
temp[i] = q[(first + i) % q.length];
}
q = temp;
first = 0;
last = N;
} /**
* Adds the item to this queue.
* @param item the item to add
*/
public void enqueue(Item item) {
// double size of array if necessary and recopy to front of array
if (N == q.length) resize(2*q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
N++;
} /**
* Removes and returns the item on this queue that was least recently added.
* @return the item on this queue that was least recently added
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = q[first];
q[first] = null; // to avoid loitering
N--;
first++;
if (first == q.length) first = 0; // wrap-around
// shrink size of array if necessary
if (N > 0 && N == q.length/4) resize(q.length/2);
return item;
} /**
* Returns the item least recently added to this queue.
* @return the item least recently added to this queue
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return q[first];
} /**
* Returns an iterator that iterates over the items in this queue in FIFO order.
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ArrayIterator();
} // an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
public boolean hasNext() { return i < N; }
public void remove() { throw new UnsupportedOperationException(); } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = q[(i + first) % q.length];
i++;
return item;
}
} /**
* Unit tests the <tt>ResizingArrayQueue</tt> data type.
*/
public static void main(String[] args) {
ResizingArrayQueue<String> q = new ResizingArrayQueue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) q.enqueue(item);
else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");
}
StdOut.println("(" + q.size() + " left on queue)");
} }

3.

 package algorithms.stacks13;

 /******************************************************************************
* 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章基础-1.3Bags, Queues, and Stacks-001可变在小的的更多相关文章

  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.4 Analysis of Algorithms-005计测试算法

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

  9. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-002如何改进算法

    1. package algorithms.analysis14; import algorithms.util.In; import algorithms.util.StdOut; /******* ...

随机推荐

  1. 使用javah生成jni 头文件和使用ndk编译so库

    1.jni 首先clean Project,在makeProject生成对应的class文件 然后点出命名框,输入命令: cd app/build/intermediates/classes/debu ...

  2. LeetCode OJ:Contains Duplicate III(是否包含重复)

    Given an array of integers, find out whether there are two distinct indices i and j in the array suc ...

  3. Kattis - redblacktree Red Black Tree (树形背包)

    问题:有一课含有n(n<=2e5)个结点的数,有m(m<=1000)个结点是红色的,其余的结点是黑色的.现从树中选若干数量的结点,其中红色的恰有k个,并且每个结点都不是其他任何另一个结点的 ...

  4. poj1463 Strategic game[树形DP]

    求一棵树每条边都被选上的点覆盖掉的最少选点数. 一条边被覆盖掉,必须他父亲和儿子中选一个..这不就是比NOIP2018D2T3还裸的暴力么.水掉. lyd给的练习题都什么**玩意儿.. code不挂了 ...

  5. python 图形化(Tkinter)

    python提供了多个图形开发界面的库,几个常用Python GUI库如下: Tkinter: Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口.T ...

  6. Laravel 传递数据到视图

    // 使用传统的方法 $view = view('greeting')->with('name', 'Victoria'); // 使用魔术方法 $view = view('greeting') ...

  7. 使用jQuery+css实现选项卡切换功能

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...

  8. PHP:json_encode 保持中文不被转为ASCII码

    echo json_encode(array('黄河之水天上来'),JSON_UNESCAPED_UNICODE);

  9. C++11 引用叠加规则和模板参数类型推导规则

    http://zm8.sm-img2.com/?src=http%3A%2F%2F***%2FArticle%2F38320&uid=57422b713ac761e653af7b327bfd9 ...

  10. web 应用 及 补充

    Highcharts 绘图配置 的函数及参数 web页面文本框修饰器 --- KindEditor web页面 之 超人性的点赞与狂踩 web页面 之 图片上传 web页面 之 评论盖楼 jQuery ...