本次作业考察利用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. 设置textView或者label的行间距方法

    一,效果图. 二,代码. RootViewController.m - (void)viewDidLoad { [super viewDidLoad]; // Do any additional se ...

  2. Robolectric Test-Drive Your Android Code

    Running tests on an Android emulator or device is slow! Building, deploying, and launching the app o ...

  3. 第一章 Android体系与系统架构

    1. Dalvik 和 ART(Android Runtime) 在Dalvik中应用好比是一辆可折叠的自行车,平时是折叠的,只有骑的时候,才需要组装起来用.在ART中应用好比是一辆组装好了的自行车, ...

  4. 处理移动端click事件300ms延迟的好方法—FastClick

    下载地址:https://github.com/ftlabs/fastclick 1.click事件为什么有延迟? “...mobile browsers will wait approximatel ...

  5. HTML5 Canvas实现刮刮卡效果实例

    HTML: <style> #canvas { border: 1px solid blue; position: absolute; left: 10px; top: 10px; bac ...

  6. Premature optimization is the root of all evil.

    For all of we programmers,we should always remember that "Premature optimization is the root of ...

  7. 关于c:\fakepath\的解决办法

    (2014.11.25 最后更新) 一.碎碎念:关于访问本地图片的路径的问题,比较典型的例子就是上传头像.在以往的解决办法中,我们大多是先将图片上传到服务器然后从服务器返回图片,显示在页面上以达到预览 ...

  8. Java如何连接到MySQL数据库的

    下载:mysql-connector-java-5.1.38.tar.gz http://dev.mysql.com/downloads/connector/j/ tar zxvf mysql-con ...

  9. SetTimer 和 OnTimer 的使用

    最近在公司做一个MFC项目,因为是MFC新手,所以在这里记录一些最近用到和学到的东西留着以后查阅. 今天遇到的一个问题是要在窗口刚刚初始化完成时自动检测一个配置文件是否存在(实际上就是检测是不是首次登 ...

  10. SGU 145.Strange People(无环K短路)

    时间:0.25s空间:4m 题意: 其实就是求无环第K短路. 输入: 给出n,m,k,分别代表,n个点,m条边,第k长路. 接下来m行,三个整数x,y,z,分别代表x,y之间有条费用为x的双向路.保证 ...