question:
deque. a double-ended queue or deque(pronounced "deck") is like a stack or a queue but supports adding and removing items at both ends. a deque stores a collection of items and supports the following api:
public class Deque<Item> implements Iterable<Item> Deque() //create an empty deque boolean isEmpty() //is the deque empty? int size() //number of items in the deque void pushLeft(Item item) //add an item to the left end void pushRight(Item item) //add an item to the right end Item popLeft() //remove an item from the left end Item popRight() //remove an item from the right endwrite a class deque that uses a double-linked list to implement this api and a class resizingarraydeque that uses a resizing array.
answer:
import edu.princeton.cs.algs4.*; public class Deque<Item> { private class Node { Item item; Node left; Node right; } private Node head; private Node tail; private int size; public Deque() { head = tail = null; size = 0; } public boolean isEmpty() { return size == 0; } public int size() { return size; } public void pushLeft(Item item) { Node node = new Node(); node.item = item; node.left = null; node.right = null; if(this.isEmpty()) { head = tail = node; } else { node.right = head; head.left = node; head = node; } size++; } public void pushRight(Item item) { Node node = new Node(); node.item = item; node.left = null; node.right = null; if(this.isEmpty()) { head = tail = node; } else { tail.right = node; node.left = tail; tail = node; } size++; } public Item popLeft() { if(this.isEmpty()) { return null; } Item item = head.item; Node temp = head; head = head.right; if(head != null)//防止为空 head.left = null; size--; return item; } public Item popRight() { if(this.isEmpty()) { return null; } Item item = tail.item; Node temp = tail; tail = tail.left; if(tail != null)//防止为空 tail.right = null; size--; return item; } public static void main(String[] args) { Deque<String> deque = new Deque<String>(); deque.pushLeft("w"); deque.pushRight("j"); deque.pushRight("c"); StdOut.println(deque.size()); StdOut.print(deque.popLeft() + "\t"); StdOut.print(deque.popLeft() + "\t"); StdOut.print(deque.popRight() + "\t"); StdOut.println("\n" + deque.size()); } }
//忘加迭代器了QAQ
//数组实现可变大小的也没做