/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
import java.util.NoSuchElementException;
import java.util.Iterator;
public class Deque<Item> implements Iterable<Item>{
private Node first, last;
private int qty;// construct an empty deque
public Deque(){}// is the deque empty?
public boolean isEmpty(){return qty ==0;}// return the number of items on the deque
public intsize(){return qty;}// add the item to the front
public voidaddFirst(Item item){if(item == null){
throw new IllegalArgumentException();}
Node oldfirst = first;
first = new Node(item);
first.next = oldfirst;if(last == null){
last = first;}else{
oldfirst.prev = first;}
qty++;}// add the item to the back
public voidaddLast(Item item){if(item == null){
throw new IllegalArgumentException();}
Node oldlast = last;
last = new Node(item);
last.prev = oldlast;if(first == null){
first = last;}else{
oldlast.next = last;}
qty++;}// remove and return the item from the front
public Item removeFirst(){if(isEmpty()){
throw new NoSuchElementException();}
Node oldfirst = first;
first = first.next;if(first != null)
first.prev = null;else
last = null;
qty--;return oldfirst.it;}// remove and return the item from the back
public Item removeLast(){if(isEmpty()){
throw new NoSuchElementException();}
Node oldlast = last;
last = last.prev;if(last != null)
last.next = null;else
first = null;
qty--;return oldlast.it;}// return an iterator over items in order from front to back
public Iterator<Item>iterator(){return new DequeIterator();}// unit testing (required)
public staticvoidmain(String[] args){}
private class DequeIterator implements Iterator<Item>{
private Node index = first;
public boolean hasNext(){return index != null;}
public Item next(){if(!hasNext()){
throw new NoSuchElementException();}
Node tmp = index;
index = index.next;return tmp.it;}
public voidremove(){
throw new UnsupportedOperationException();}}
private class Node {
private final Item it;
private Node next;
private Node prev;
public Node(Item item){
it = item;}}}
Randomized Queues
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */importedu.princeton.cs.algs4.StdRandom;importjava.util.Iterator;importjava.util.NoSuchElementException;publicclassRandomizedQueue<Item>implementsIterable<Item>{privateItem[] arr;privateint num;//@SuppressWarnings("unchecked")// construct an empty randomized queuepublicRandomizedQueue(){
arr =(Item[])newObject[1];}//@SuppressWarnings("unchecked")privatevoidresize(int capacity){Item[] copy =(Item[])newObject[capacity];for(int i =0; i < num; i++){
copy[i]= arr[i];}
arr = copy;}// is the randomized queue empty?publicbooleanisEmpty(){return num ==0;}// return the number of items on the randomized queuepublicintsize(){return num;}// add the itempublicvoidenqueue(Item item){if(item ==null)thrownewIllegalArgumentException();if(num == arr.length)resize(2* num);
arr[num]= item;
num++;}// remove and return a random itempublicItemdequeue(){if(isEmpty()){thrownewNoSuchElementException();}if(num < arr.length /4){resize(arr.length /2);}int n =StdRandom.uniform(num);Item temp = arr[n];
arr[n]= arr[num -1];
arr[num -1]=null;
num--;return temp;}// return a random item (but do not remove it)publicItemsample(){if(isEmpty()){thrownewNoSuchElementException();}int n =StdRandom.uniform(num);return arr[n];}// return an independent iterator over items in random orderpublicIterator<Item>iterator(){returnnewQueueIterator();}// unit testing (required)publicstaticvoidmain(String[] args){}privateclassQueueIteratorimplementsIterator<Item>{privatefinalint[] arrshf;privateint n;publicQueueIterator(){
arrshf =newint[num];for(int i =0; i < num; i++){
arrshf[i]= i;}StdRandom.shuffle(arrshf);}publicbooleanhasNext(){return n < num;}publicItemnext(){if(!hasNext()){thrownewNoSuchElementException();}Item temp = arr[arrshf[n]];
n++;return temp;}publicvoidremove(){thrownewUnsupportedOperationException();}}}
Permutation
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */importedu.princeton.cs.algs4.StdIn;importjava.util.Iterator;publicclassPermutation{publicstaticvoidmain(String[] args){if(args.length !=1)return;int num =Integer.parseInt(args[0]);RandomizedQueue<String> raqu =newRandomizedQueue<String>();while(!StdIn.isEmpty()){String str =StdIn.readString();
raqu.enqueue(str);}Iterator<String> it = raqu.iterator();while(it.hasNext()&& num >0){System.out.println(it.next());
num--;}}}
总结
Randomized Queues 涉及到泛型数组,强制转化类型会有编译warning,成功创建泛型数组的唯一方式是创建一个类型擦除的数组,然后转型。注意我们不能直接创建泛型数组,但可以定义泛型数组的引用,其实使用 Class 对象作为类型标识是更好的设计。