Deques and Randomized Queues

Deques and Randomized Queues


Deques

/* *****************************************************************************
 *  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 int size() {
        return qty;
    }

    // add the item to the front
    public void addFirst(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 void addLast(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 static void main(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 void remove() {
            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
 **************************************************************************** */

import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class RandomizedQueue<Item> implements Iterable<Item> {
    private Item[] arr;
    private int num;

    //@SuppressWarnings("unchecked")
    // construct an empty randomized queue
    public RandomizedQueue() {
        arr = (Item[]) new Object[1];
    }

    //@SuppressWarnings("unchecked")
    private void resize(int capacity) {
        Item[] copy = (Item[]) new Object[capacity];
        for (int i = 0; i < num; i++) {
            copy[i] = arr[i];
        }
        arr = copy;
    }

    // is the randomized queue empty?
    public boolean isEmpty() {
        return num == 0;
    }

    // return the number of items on the randomized queue
    public int size() {
        return num;
    }

    // add the item
    public void enqueue(Item item) {
        if (item == null)
            throw new IllegalArgumentException();
        if (num == arr.length)
            resize(2 * num);
        arr[num] = item;
        num++;
    }

    // remove and return a random item
    public Item dequeue() {
        if (isEmpty()) {
            throw new NoSuchElementException();
        }
        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)
    public Item sample() {
        if (isEmpty()) {
            throw new NoSuchElementException();
        }
        int n = StdRandom.uniform(num);
        return arr[n];
    }

    // return an independent iterator over items in random order
    public Iterator<Item> iterator() {
        return new QueueIterator();
    }

    // unit testing (required)
    public static void main(String[] args) {

    }

    private class QueueIterator implements Iterator<Item> {

        private final int[] arrshf;
        private int n;

        public QueueIterator() {
            arrshf = new int[num];
            for (int i = 0; i < num; i++) {
                arrshf[i] = i;
            }
            StdRandom.shuffle(arrshf);
        }

        public boolean hasNext() {
            return n < num;
        }

        public Item next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            Item temp = arr[arrshf[n]];
            n++;
            return temp;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

    }
}


Permutation

/* *****************************************************************************
 *  Name:              Ada Lovelace
 *  Coursera User ID:  123456
 *  Last modified:     October 16, 1842
 **************************************************************************** */

import edu.princeton.cs.algs4.StdIn;

import java.util.Iterator;

public class Permutation {
    public static void main(String[] args) {
        if (args.length != 1)
            return;
        int num = Integer.parseInt(args[0]);
        RandomizedQueue<String> raqu = new RandomizedQueue<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 对象作为类型标识是更好的设计。

具体参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值