本次作业考察利用array 或者linked list 实现规定时间复杂度的queue 和stack, 不能使用java 自带的stack 和queue. 目的是让我们掌握自己设计的函数的复杂度。

Deque成功的关键是

1. 选择合适的数据结构,本题选择doubly LinkedList.

2. 自己写测试代码,测试各种情况。addLast, removeFirst 等等,尤其注意边界情况。

Java code:

//Deque - should be implemented using a doubly linked list
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.NoSuchElementException; /*The goal of this assignment is to implement data types from first principles,
*using resizing arrays and linked lists.
*/
/*
* 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.
*
* Performance requirements.
* Your deque implementation must support each deque operation in constant worst-case time.
* A deque containing N items must use at most 48N + 192 bytes of memory.
* and use space proportional to the number of items currently in the deque.
*
* Additionally, your iterator implementation must support each operation (including construction) in constant worst-case time.
*/
public class Deque<Item> implements Iterable<Item> {
private int N; // size of the stack
private Node first;
private Node last; // helper linked list class
private class Node {
private Item item;
private Node prev;
private Node next;
} // construct an empty deque
public Deque() {
N = 0;
first = null;
last = null;
} // is the deque empty?
public boolean isEmpty() {
return N == 0;
} // return the number of items on the deque
public int size() {
return N;
} //Throw a java.lang.NullPointerException if the client attempts to add a null item
public void addFirst(Item item) { // add the item to the front
if(item == null) {
throw new NullPointerException("add a null item");
}
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
first.prev = null;
if(isEmpty()) {
last = first;
} else {
oldfirst.prev = first;
}
N++;
} //Throw a java.lang.NullPointerException if the client attempts to add a null item
public void addLast(Item item) { // add the item to the end
if(item == null) {
throw new NullPointerException("add a null item");
}
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
last.prev = oldlast;
if(isEmpty()) {
first = last;
}else {
oldlast.next = last;
}
N++;
} //remove and return the item from the front
// throw a java.util.NoSuchElementException if the client attempts to remove an item from an empty deque
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException("Deque underflow");
}
Item item = first.item; // save item to return
Node oldfirst = first;
first = first.next; // delete first node
oldfirst = null;
if(first == null) {
last = null;
} else {
first.prev = null;
}
N--;
return item;
} // remove and return the item from the end
// throw a java.util.NoSuchElementException if the client attempts to remove an item from an empty deque
public Item removeLast() {
if (isEmpty()) {
throw new NoSuchElementException("Deque underflow");
}
Item item = last.item; //save item to return
Node oldlast = last;
last = last.prev;
oldlast.prev = null; if(last != null) {
last.next = null;
}else {
first = null;
}
oldlast = null;
N--;
return item;
} // return an iterator over items in order from front to end
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();
} public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Item item = current.item;
current = current.next;
return item;
}
} public static void main(String[] args) { // unit testing
//testSimpleAddRemove();
testAddRemoveallItems();
}
private static void testSimpleAddRemove() {
Deque<Integer> d = new Deque<Integer>();
d.addFirst(10);
d.addFirst(20);
d.addFirst(30);
d.addLast(100);
d.addLast(101);
d.addLast(102); assert d.size() == 6;
System.out.println(d.size()); Iterator i = d.iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
System.out.println(""); System.out.println("d.removeFirst() is " + d.removeFirst());
System.out.println("d.removeLast() is " + d.removeLast());
System.out.println(d.size()); i = d.iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
System.out.println("");
} private static void testAddRemoveallItems() {
Deque<Integer> d = new Deque<Integer>(); d.addFirst(10);
//d.addLast(20); Iterator i = d.iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
System.out.println("");
System.out.println("d.size is " + d.size());
//System.out.println("d.removeFirst() is " + d.removeFirst());
System.out.println("d.removeLast() is " + d.removeLast());
System.out.println("d.size is " + d.size());
}
}

AlgorithmsI PA2: Randomized Queues and Deques Deque的更多相关文章

  1. AlgorithmsI PA2: Randomized Queues and Deques RandomizedQueue

    RandomizedQueue 有几个关键点: 1. 选择合适的数据结构,因为需要任意位置删除元素,Linked list 做不到,必须使用resizing arrays. 2. resizing 的 ...

  2. AlgorithmsI PA2: Randomized Queues and Deques Subset

    本题的bonus是 因此方法是queue的size 达到了K, 就停止增加元素,保证queue.size() 最大时只有k. Java code: import edu.princeton.cs.al ...

  3. Programming Assignment 2: Randomized Queues and Deques

    实现一个泛型的双端队列和随机化队列,用数组和链表的方式实现基本数据结构,主要介绍了泛型和迭代器. Dequeue. 实现一个双端队列,它是栈和队列的升级版,支持首尾两端的插入和删除.Deque的API ...

  4. Programming Assignment 2: Deques and Randomized Queues

    编程作业二 作业链接:Deques and Randomized Queues & Checklist 我的代码:Deque.java & RandomizedQueue.java & ...

  5. Deques and Randomized Queues

    1. 题目重述 完成三个程序,分别是双向队列,随机队列,和随机队列读取文本并输出k个数. 2. 分析 2.1 双向队列 题目的性能要求是,操作时间O(1),内存占用最大48n+192byte. 当使用 ...

  6. STL deque详解

    英文原文:http://www.codeproject.com/Articles/5425/An-In-Depth-Study-of-the-STL-Deque-Container 绪言 这篇文章深入 ...

  7. The Swiss Army Knife of Data Structures … in C#

    "I worked up a full implementation as well but I decided that it was too complicated to post in ...

  8. Java 性能调优指南之 Java 集合概览

    [编者按]本文作者为拥有十年金融软件开发经验的 Mikhail Vorontsov,文章主要概览了所有标准 Java 集合类型.文章系国内 ITOM 管理平台 OneAPM 编译呈现,以下为正文: 本 ...

  9. Coursera Algorithms Programming Assignment 2: Deque and Randomized Queue (100分)

    作业原文:http://coursera.cs.princeton.edu/algs4/assignments/queues.html 这次作业与第一周作业相比,稍微简单一些.有三个编程练习:双端队列 ...

随机推荐

  1. short a = 128, byte b = (byte)a 强制类型转换

    package 笔试; public class ShortToByte { /** * @param args */ public static void main(String[] args) { ...

  2. iOS 数据持久化(1):属性列表与对象归档

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css); @import url(/ ...

  3. iOS原生CIFilter创建二维码

    iOS原生CIFilter创建二维码 2016-05-31 未来C iOS原生CIFilter创建二维码 关于二维码生成,网上也是有很多,很早以前的第三方库大多数都是通过C++写,也是有的如zxing ...

  4. 【转载】Shared Configuration

    Introduction The Internet changes the ways in which companies handle their day-to-day business and h ...

  5. 《REWORK》启示录 招聘笔杆子——程序员为什么值得写博客

    Hire Great Writers 仿佛这是写给自己看的,不过这在其中也有着相当有趣的意义 .虽然自己算是一个能写的人,或许这算是一种不算才华的才华,写博文的意义通常不会在于去描述自己怎样,怎样.通 ...

  6. 10.18 noip模拟试题

    分火腿 (hdogs.pas/.c/.cpp) 时间限制:1s:内存限制 64MB 题目描述: 小月言要过四岁生日了,她的妈妈为她准备了n根火腿,她想将这些火腿均分给m位小朋友,所以她可能需要切火腿. ...

  7. 通过WebClient/HttpWebRequest实现http的post/get方法

    ///<summary>/// 通过WebClient类Post数据到远程地址,需要Basic认证: /// 调用端自己处理异常 ///</summary>///<par ...

  8. CentOS 5.4下的Memcache安装步骤(Linux+Nginx+PHP+Memcached)

    原文链接:http://www.jb51.net/article/29668.htm

  9. eclipse下:selenium+python自动化之Chrome driver

    1.下载chromedriver.exe文件: 2.下载的chromedriver.exe文件放置在chrome的安装目录下XXX\Chrome\Application\ ; 3.设置path环境变量 ...

  10. jQuery慢慢啃之事件(七)

    1.ready(fn)//当DOM载入就绪可以查询及操纵时绑定一个要执行的函数. $(document).ready(function(){ // 在这里写你的代码...}); 使用 $(docume ...