「数据结构」普林斯顿算法课第二周作业 Algorithm I, Princeton
编程作业: Deques and Randomized Queues
Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to generics and iterators.
Dequeue. A double-ended queue or deque (pronounced “deck”) is a generalization of a stack and a queue that supports adding and removing items from either the front or the back of the data structure.
思路
对于第一个程序,只要在Node
内部类中增加一个pre
即可。
第二个RandomizedQueue
的话,需定一个范型数组用于保存信息。
第三个程序Permutation
要用Integer.parseInt(args[0])
获取命令行输入的数字。
Deque.java
/* *****************************************************************************
* Name: Albert
* Date: 22 Aug
* Description:
**************************************************************************** */
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Node first;
private Node last;
private int n; // total number
private class Node {
Item item;
Node pre; // add
Node next;
}
// construct an empty deque
public Deque() {
first = null;
last = null;
n = 0;
}
// is the deque empty?
public boolean isEmpty() {
return n == 0;
}
// return the number of items on the deque
public int size() {
return n;
}
// add the item to the front
public void addFirst(Item item) {
if (item == null)
throw new IllegalArgumentException("Input is null.");
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
first.pre = null;
if (isEmpty()) last = first;
else oldfirst.pre = first;
n++;
}
// add the item to the back
public void addLast(Item item) {
if (item == null)
throw new IllegalArgumentException("Input is null!");
Node oldlast = last;
last = new Node();
last.item = item;
last.pre = oldlast;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
n++;
}
// remove and return the item from the front
public Item removeFirst() {
if (isEmpty())
throw new NoSuchElementException("The deque is empty!");
Item item = first.item;
first = first.next;
n--;
if (isEmpty()) last = null;
else first.pre = null;
return item;
}
// remove and return the item from the back
public Item removeLast() {
if (isEmpty())
throw new NoSuchElementException("The deque is empty!");
Item item = last.item;
last = last.pre;
n--;
if (isEmpty()) first = null;
else last.next = null;
return item;
}
// return an iterator over items in order from front to back
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException("Unsupported operation!");
}
public Item next() {
if (isEmpty())
throw new NoSuchElementException("The deque is empty!");
Item item = current.item;
current = current.next;
return item;
}
}
// unit testing (required)
public static void main(String[] args) {
Deque<Integer> deque = new Deque<Integer>();
for (int i = 0; i < 10; i++) {
deque.addFirst(i);
}
for (int i = 10; i < 20; i++) {
deque.addLast(i);
}
StdOut.println(deque.size());
StdOut.println(deque.removeFirst());
StdOut.println(deque.size());
StdOut.println(deque.removeLast());
StdOut.println(deque.size());
}
}
RandomizedQueue.java
/* *****************************************************************************
* Name: Albert
* Date: 23 Aug
* Description:
**************************************************************************** */
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] randomizedQueue;
private int n;
// construct an empty randomized queue
public RandomizedQueue() {
randomizedQueue = (Item[]) new Object[2];
n = 0;
}
// is the randomized queue empty?
public boolean isEmpty() {
return n == 0;
}
// return the number of items on the randomized queue
public int size() {
return n;
}
private void resize(int capacity) {
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
temp[i] = randomizedQueue[i];
}
randomizedQueue = temp;
}
// add the item
public void enqueue(Item item) {
if (item == null)
throw new java.lang.IllegalArgumentException();
if (n == randomizedQueue.length)
resize(2 * randomizedQueue.length);
randomizedQueue[n++] = item;
}
// remove and return a random item
public Item dequeue() {
if (isEmpty())
throw new NoSuchElementException();
int num = StdRandom.uniform(n);
Item item = randomizedQueue[num];
if (num != n - 1)
randomizedQueue[num] = randomizedQueue[n - 1];
randomizedQueue[n - 1] = null;
n--;
if (n > 0 && n == randomizedQueue.length / 4)
resize(randomizedQueue.length / 2);
return item;
}
// return a random item (but do not remove it)
public Item sample() {
if (isEmpty())
throw new NoSuchElementException();
return randomizedQueue[StdRandom.uniform(n)];
}
// return an independent iterator over items in random order
public Iterator<Item> iterator() {
return new ArrayIterator();
}
private class ArrayIterator implements Iterator<Item> {
private int index = 0;
final Item[] items;
public ArrayIterator() {
items = (Item[]) new Object[n];
for (int i = 0; i < n; i++) {
items[i] = randomizedQueue[i];
}
StdRandom.shuffle(items);
}
public boolean hasNext() {
return index < n;
}
public void remove() {
throw new UnsupportedOperationException("Unsupported operation!");
}
public Item next() {
if (isEmpty())
throw new NoSuchElementException("The RandomizedQueue is empty!");
return items[index++];
}
}
// unit testing (required)
public static void main(String[] args) {
RandomizedQueue<String> randomizedQueue = new RandomizedQueue<String>();
StdOut.println("size:" + randomizedQueue.size());
randomizedQueue.enqueue("Hello");
StdOut.println("size:" + randomizedQueue.size());
randomizedQueue.enqueue("World");
StdOut.println("size:" + randomizedQueue.size());
randomizedQueue.enqueue("!");
StdOut.println("size:" + randomizedQueue.size());
StdOut.println(randomizedQueue.sample());
randomizedQueue.dequeue();
StdOut.println("size:" + randomizedQueue.size());
Iterator<String> it = randomizedQueue.iterator();
while (it.hasNext()) {
String elt = it.next();
System.out.print(elt + " ");
}
}
}
Permutation.java
/* *****************************************************************************
* Name: Albert
* Date: 23 Aug
* Description:
**************************************************************************** */
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Permutation {
public static void main(String[] args) {
RandomizedQueue<String> randomizedQueue = new RandomizedQueue<String>();
int num = Integer.parseInt(args[0]);// important!
String item;
while (!StdIn.isEmpty()) {
item = StdIn.readString();
randomizedQueue.enqueue(item);
}
for (String s : randomizedQueue) {
if (num == 0)
break;
StdOut.println(s);
num--;
}
}
}