算法Sedgewick第四版-第1章基础-011一用链表实现bag、queue、stack
1.
package algorithms.ADT; /******************************************************************************
* Compilation: javac Bag.java
* Execution: java Bag < input.txt
* Dependencies: StdIn.java StdOut.java
*
* A generic bag or multiset, implemented using a singly-linked list.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java Bag < tobe.txt
* size of bag = 14
* is
* -
* -
* -
* that
* -
* -
* be
* -
* to
* not
* or
* be
* to
*
******************************************************************************/ import java.util.Iterator;
import java.util.NoSuchElementException; import algorithms.util.StdIn;
import algorithms.util.StdOut; /**
* The <tt>Bag</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 singly-linked list with a static nested class Node.
* See {@link LinkedBag} for the version from the
* textbook that uses a non-static nested class.
* The <em>add</em>, <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
*
* @param <Item> the generic type of an item in this bag
*/
public class Bag<Item> implements Iterable<Item> {
private Node<Item> first; // beginning of bag
private int N; // number of elements in bag // helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
} /**
* Initializes an empty bag.
*/
public Bag() {
first = null;
N = 0;
} /**
* Returns true if this bag is empty.
*
* @return <tt>true</tt> if this bag is empty;
* <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return first == null;
} /**
* Returns the number of items in this bag.
*
* @return the number of items in this bag
*/
public int size() {
return N;
} /**
* Adds the item to this bag.
*
* @param item the item to add to this bag
*/
public void add(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
N++;
} /**
* Returns an iterator that iterates over the items in this bag in arbitrary order.
*
* @return an iterator that iterates over the items in this bag in arbitrary order
*/
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
} // an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current; public ListIterator(Node<Item> first) {
current = first;
} public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
} /**
* Unit tests the <tt>Bag</tt> data type.
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
bag.add(item);
} StdOut.println("size of bag = " + bag.size());
for (String s : bag) {
StdOut.println(s);
}
} }
2.
package algorithms.ADT; /******************************************************************************
* Compilation: javac Queue.java
* Execution: java Queue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a linked list.
*
* % java Queue < 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>Queue</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 singly-linked list with a static nested class for
* linked-list nodes. See {@link LinkedQueue} for the version from the
* textbook that uses a non-static nested class.
* The <em>enqueue</em>, <em>dequeue</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take 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
*
* @param <Item> the generic type of an item in this queue
*/
public class Queue<Item> implements Iterable<Item> {
private Node<Item> first; // beginning of queue
private Node<Item> last; // end of queue
private int N; // number of elements on queue // helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
} /**
* Initializes an empty queue.
*/
public Queue() {
first = null;
last = null;
N = 0;
} /**
* Returns true if this queue is empty.
*
* @return <tt>true</tt> if this queue is empty; <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return first == null;
} /**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {
return N;
} /**
* Returns the item least recently added to this queue.
*
* @return the item least recently added to this queue
* @throws NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
} /**
* Adds the item to this queue.
*
* @param item the item to add
*/
public void enqueue(Item item) {
Node<Item> oldlast = last;
last = new Node<Item>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
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 NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null; // to avoid loitering
return item;
} /**
* Returns a string representation of this queue.
*
* @return the sequence of items in FIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
} /**
* 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 ListIterator<Item>(first);
} // an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current; public ListIterator(Node<Item> first) {
current = first;
} public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
} /**
* Unit tests the <tt>Queue</tt> data type.
*/
public static void main(String[] args) {
Queue<String> q = new Queue<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.ADT; /******************************************************************************
* Compilation: javac Stack.java
* Execution: java Stack < input.txt
* Dependencies: StdIn.java StdOut.java
*
* A generic stack, implemented using a singly-linked list.
* Each stack element is of type Item.
*
* This version uses a static nested class Node (to save 8 bytes per
* Node), whereas the version in the textbook uses a non-static nested
* class (for simplicity).
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java Stack < 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>Stack</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 singly-linked list with a static nested class for
* linked-list nodes. See {@link LinkedStack} for the version from the
* textbook that uses a non-static nested class.
* The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take 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
*
* @param <Item> the generic type of an item in this stack
*/
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int N; // size of the stack // helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
} /**
* Initializes an empty stack.
*/
public Stack() {
first = null;
N = 0;
} /**
* Returns true if this stack is empty.
*
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
} /**
* Returns the number of items in this stack.
*
* @return the number of items in this stack
*/
public int size() {
return N;
} /**
* Adds the item to this stack.
*
* @param item the item to add
*/
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
N++;
} /**
* Removes and returns the item most recently added to this stack.
*
* @return the item most recently added
* @throws NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
N--;
return item; // return the saved item
} /**
* Returns (but does not remove) the item most recently added to this stack.
*
* @return the item most recently added to this stack
* @throws NoSuchElementException if this stack is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
} /**
* Returns a string representation of this stack.
*
* @return the sequence of items in this stack in LIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
} /**
* 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 ListIterator<Item>(first);
} // an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current; public ListIterator(Node<Item> first) {
current = first;
} public boolean hasNext() {
return current != null;
} public void remove() {
throw new UnsupportedOperationException();
} public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
} /**
* Unit tests the <tt>Stack</tt> data type.
*/
public static void main(String[] args) {
Stack<String> s = new Stack<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章基础-011一用链表实现bag、queue、stack的更多相关文章
- 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的
1. package algorithms.stacks13; /******************************************************************* ...
- 算法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.4 Analysis of Algorithms-005计测试算法
1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...
随机推荐
- 项目管理理论与实践(4)——UML应用(上)
本篇文章介绍UML的相关知识.参考<UML从入门到精通> 一.UML综述 1. UML简介 统一建模语言(UML)是一个通用的可视化建模语言,用于对软件进行描述.可视化处理.构造和建立软件 ...
- spring MVC HandlerInterceptorAdapter
SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那 ...
- 201621123014《Java程序设计》第六周学习总结
1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图或相关笔记,对面向对象思想进行一个总结. 答: 注1:关键词与内容不求多,但概念之间的联系 ...
- hdoj-1004-Let the Balloon Rise(map排序)
map按照value排序 #include <iostream> #include <algorithm> #include <cstring> #include ...
- Codeforces Round #286 (Div. 2)B. Mr. Kitayuta's Colorful Graph(dfs,暴力)
数据规模小,所以就暴力枚举每一种颜色的边就行了. #include<iostream> #include<cstdio> #include<cstdlib> #in ...
- linux shell 学习笔记--变量声明与赋值,循环
Bash 变量是不分类型的 ------------------------ 不像其他程序语言一样,Bash 并不对变量区分"类型".本质上,Bash 变量都是字符串. 但是依赖于 ...
- 用Json Template在Azure上创建Cisco CSR路由器
Azure的ARM模式可以通过Json的模板创建VM.本文以Cisco的CSR的image为例,介绍如何用Json的创建VM. 一.Cisco CSR的Image 首先把Cisco CSR的image ...
- Win10 Bash更改默认用户
Win10已经支持Ubuntu的Bash了. 在cmd中输入bash就可以进入bash界面.但此时是普通用户登录的. 如果希望更改默认的登录用户,可以在cmd中更改. 具体的命令是: lxrun /s ...
- 第二届PHP全球开发者大会(含大会的PPT)
PHP全球开发者大会于2016年5月14日至15日在北京召开 更多现场图片请猛击: http://t.cn/RqeP7y9 , http://t.cn/RqD8Typ 最后,这次大会的PPT可以在这 ...
- svn更新报错:出现skipped:目标路径
skipped 意为:跳过此目标文件: 一般出现在目标文件被删除后,重新更新情况下: 解决办法及结果: 1,回到此目标文件的上一层文件夹,team-clean up,结果不成功 2,回到此目标文件的上 ...