本次作业考察利用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. Annotation Type @bean,@Import,@configuration使用--官方文档

    @Target(value={METHOD,ANNOTATION_TYPE}) @Retention(value=RUNTIME) @Documented public @interface Bean ...

  2. spring mvc DispatcherServlet详解之一--request通过HandlerMaping获取控制器Controller过程

    整个spring mvc的架构如下图所示: 现在来讲解DispatcherServletDispatcherServlet的第一步:获取控制器. HandlerMapping HandlerMappi ...

  3. IE6与W3C标准的盒模型差异

    盒子模型(Box Model)是 CSS 的核心,现代 Web 布局设计简单说就是一堆盒子的排列与嵌套,掌握了盒子模型与它们的摆放控制,会发现再复杂的页面也不过如此,然而,任何美好的事物都有缺憾,盒子 ...

  4. Java基础知识强化13:Java中单例模式案例使用(懒汉式)

    1.古往今来历史上皇帝通常只有一人.为了保证其唯一性,古人采用增加"防伪标识"的办法,如玉玺.更为简单的办法就是限制皇帝的创建.本案例中就是使用单例模式从而保证皇帝的唯一性.实例运 ...

  5. Socket.IO 概述

    为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/SJQ. http://www.cnblogs.com/shijiaqi1066/p/3826251.html ...

  6. 9.20 noip模拟试题

      Problem 1 双色球(ball.cpp/c/pas) [题目描述] 机房来了新一届的学弟学妹,邪恶的chenzeyu97发现一位学弟与他同名,于是他当起了善良的学长233 “来来来,学弟,我 ...

  7. noi1816 画家问题(技巧搜索Dfs)

    /* Problem 画家问题 假设一个ans数组存的是对每一个点的操作 0表示不图 1表示图 那么 对于原图 g 操作第三行时对第一行没有影响 同样往下类似的 所以 假设我们知道了ans的第一行就是 ...

  8. C++ hello world

    日文版本的vs 2008 , 在 < 新建 里面先创建一个项目 然后点击项目去创建一个C++的主启动文件 选择创建的文件类型 然后在文件里面写入代码 #include<iostream&g ...

  9. (转)修改ECSHOP前后台的title中的ecshop

    前台部分: 1:去掉头部TITLE部分的ECSHOP演示站 Powered by ecshop 前者在后台商店设置 - 商店标题修改 后者打开includes/lib_main.php $page_t ...

  10. Oracle 左连接、右连接、全外连接、(+)号作用、inner join(等值连接) (转载)

    Oracle  外连接 (1)左外连接 (左边的表不加限制)       (2)右外连接(右边的表不加限制)       (3)全外连接(左右两表都不加限制) 外连接(Outer Join) oute ...