本次作业考察利用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. ios-点击屏幕,隐藏键盘

    ios-点击屏幕,隐藏键盘 - (void)getFirstRegist{ //结束键盘编辑 __weak typeof(self)weakSelf = self; UITapGestureRecog ...

  2. Java基础知识强化01:short s = 1; s = s + 1;与short s = 1; s += 1;

    1.short s = 1; s = s + 1;有没有问题?如果有怎么解决?    short s = 1; s += 1;有没有问题?如果有怎么解决? 2.理解: short s=1;  s=s+ ...

  3. centos6.5 64位 openvpn安装配置

    1 查看系统版本 2 cat /etc/redhat-release 3 CentOS release 6.5 (Final) 4 5 查看内核和cpu架构 6 uname -rm 7 2.6.32- ...

  4. Android端上传图片到后台,存储到数据库中 详细代码

    首先点击头像弹出popwindow,点击相册,相机,调用手机自带的裁剪功能,然后异步任务类访问服务器,上传头像,保存到数据库中, 下面写出popwindow的代码 //设置popwindow publ ...

  5. php100视频原始地址列表整理:

    php100视频原始地址列表整理: 教程名称 . 1:环境配置与代码调试 2:PHP的数据类型与源码调试 3:常用PHP运算类型介绍与应用 4: PHP条件语句介绍与应用 5:PHP循环语句的介绍与应 ...

  6. Solaris用户管理(一):用户与组管理

    Solaris用户管理(一):用户与组管理  2008-07-01 09:19 用户管理是系统管理的基础.Solaris中不但支持传统Unix所支持的用户和组的概念,还从Solaris 8开始引入了基 ...

  7. php验证是否为手机端还是PC

    <?php $forasp = strtolower($_SERVER['HTTP_USER_AGENT']); if(strpos($forasp,'mobile')==true) { ech ...

  8. 利用Graphviz 画结构图[转]

    转自:http://www.cnblogs.com/sld666666/archive/2010/06/25/1765510.html 利用Graphviz 画结构图   1. Graphviz介绍 ...

  9. 进程识别号(PID)的理解

    PID(Process Identification)操作系统里指进程识别号,也就是进程标识符.操作系统里每打开一个程序都会创建一个进程ID,即PID. PID(进程控制符)英文全称为Process ...

  10. 【POJ2887】【块状链表】Big String

    Description You are given a string and supposed to do some string manipulations. Input The first lin ...