From 73d2d52f4a106ca5467576178c642f351be724b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Zurcher?= Date: Wed, 6 Mar 2013 00:20:37 +0100 Subject: Algorithms-I : 2-Randomized_Queues_Deques: add Deque.java --- .../Part-I/2-Randomized_Queues_Deques/Deque.java | 118 +++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 Algorithms/Part-I/2-Randomized_Queues_Deques/Deque.java diff --git a/Algorithms/Part-I/2-Randomized_Queues_Deques/Deque.java b/Algorithms/Part-I/2-Randomized_Queues_Deques/Deque.java new file mode 100644 index 0000000..e8a17de --- /dev/null +++ b/Algorithms/Part-I/2-Randomized_Queues_Deques/Deque.java @@ -0,0 +1,118 @@ +/* vim: set expandtab tabstop=4 shiftwidth=4 : */ + +import java.util.Iterator; + +public class Deque implements Iterable +{ + private Node head; + private Node tail; + private int n; + + private class Node + { + Item item; + Node next; + Node prev; + } + + // construct an empty deque + public Deque() + { + head = null; + tail = null; + n = 0; + } + + // is the deque empty? + public boolean isEmpty() + { + return (head == null); + } + + // return the number of items on the deque + public int size() + { + return n; + } + + // insert the item at the front + public void addFirst(Item item) + { + if (item == null) throw new java.lang.NullPointerException(); + Node node = new Node(); + node.item = item; + node.next = head; + node.prev = null; + head = node; + if (tail == null) tail = head; + n++; + } + + // insert the item at the end + public void addLast(Item item) + { + if (item == null) throw new java.lang.NullPointerException(); + Node node = new Node(); + node.item = item; + node.next = null; + node.prev = tail; + if (tail == null) + { + head = tail = node; + } + else + { + tail.next = node; + tail = tail.next; + } + n++; + } + + // delete and return the item at the front + public Item removeFirst() + { + if (head == null) throw new java.util.NoSuchElementException(); + Item item = head.item; + if (tail == head) tail = tail.next; + head = head.next; + head.prev = null; + n--; + return item; + } + + // delete and return the item at the end + public Item removeLast() + { + if (tail == null) throw new java.util.NoSuchElementException(); + Item item = tail.item; + if (head == tail) + { + head = tail = null; + } + else + { + tail = tail.prev; + tail.next = null; + } + n--; + return item; + } + + // return an iterator over items in order from front to end + public Iterator iterator() { return new DequeIterator(); } + + private class DequeIterator implements Iterator + { + private Node current = head; + + public boolean hasNext() { return current != null; } + public void remove() { throw new java.lang.UnsupportedOperationException(); } + public Item next() + { + if (current == null) throw new java.util.NoSuchElementException(); + Item item = current.item; + current = current.next; + return item; + } + } +} -- cgit v1.1-2-g2b99