package algorithms.ADT;

 /******************************************************************************
* Compilation: javac DoublyLinkedList.java
* Execution: java DoublyLinkedList
* Dependencies: StdOut.java
*
* A list implemented with a doubly linked list. The elements are stored
* (and iterated over) in the same order that they are inserted.
*
* % java DoublyLinkedList 10
* 10 random integers between 0 and 99
* 24 65 2 39 86 24 50 47 13 4
*
* add 1 to each element via next() and set()
* 25 66 3 40 87 25 51 48 14 5
*
* multiply each element by 3 via previous() and set()
* 75 198 9 120 261 75 153 144 42 15
*
* remove elements that are a multiple of 4 via next() and remove()
* 75 198 9 261 75 153 42 15
*
* remove elements that are even via previous() and remove()
* 75 9 261 75 153 15
*
******************************************************************************/ import java.util.ListIterator;
import java.util.NoSuchElementException; import algorithms.util.StdOut;
import algorithms.util.StdRandom; public class DoublyLinkedList<Item> implements Iterable<Item> {
private int N; // number of elements on list
private Node pre; // sentinel before first item
private Node post; // sentinel after last item public DoublyLinkedList() {
pre = new Node();
post = new Node();
pre.next = post;
post.prev = pre;
} // linked list node helper data type
private class Node {
private Item item;
private Node next;
private Node prev;
} public boolean isEmpty() { return N == 0; }
public int size() { return N; } // add the item to the list
public void add(Item item) {
Node last = post.prev;
Node x = new Node();
x.item = item;
x.next = post;
x.prev = last;
post.prev = x;
last.next = x;
N++;
} public ListIterator<Item> iterator() { return new DoublyLinkedListIterator(); } // assumes no calls to DoublyLinkedList.add() during iteration
private class DoublyLinkedListIterator implements ListIterator<Item> {
private Node current = pre.next; // the node that is returned by next()
private Node lastAccessed = null; // the last node to be returned by prev() or next()
// reset to null upon intervening remove() or add()
private int index = 0; public boolean hasNext() { return index < N; }
public boolean hasPrevious() { return index > 0; }
public int previousIndex() { return index - 1; }
public int nextIndex() { return index; } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
lastAccessed = current;
Item item = current.item;
current = current.next;
index++;
return item;
} public Item previous() {
if (!hasPrevious()) throw new NoSuchElementException();
current = current.prev;
index--;
lastAccessed = current;
return current.item;
} // replace the item of the element that was last accessed by next() or previous()
// condition: no calls to remove() or add() after last call to next() or previous()
public void set(Item item) {
if (lastAccessed == null) throw new IllegalStateException();
lastAccessed.item = item;
} // remove the element that was last accessed by next() or previous()
// condition: no calls to remove() or add() after last call to next() or previous()
public void remove() {
if (lastAccessed == null) throw new IllegalStateException();
Node x = lastAccessed.prev;
Node y = lastAccessed.next;
x.next = y;
y.prev = x;
N--;
if (current == lastAccessed)
current = y;
else
index--;
lastAccessed = null;
} // add element to list
public void add(Item item) {
Node x = current.prev;
Node y = new Node();
Node z = current;
y.item = item;
x.next = y;
y.next = z;
z.prev = y;
y.prev = x;
N++;
index++;
lastAccessed = null;
} } public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
} // a test client
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // add elements 1, ..., N
StdOut.println(N + " random integers between 0 and 99");
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
for (int i = 0; i < N; i++)
list.add(StdRandom.uniform(100));
StdOut.println(list);
StdOut.println(); ListIterator<Integer> iterator = list.iterator(); // go forwards with next() and set()
StdOut.println("add 1 to each element via next() and set()");
while (iterator.hasNext()) {
int x = iterator.next();
iterator.set(x + 1);
}
StdOut.println(list);
StdOut.println(); // go backwards with previous() and set()
StdOut.println("multiply each element by 3 via previous() and set()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
iterator.set(x + x + x);
}
StdOut.println(list);
StdOut.println(); // remove all elements that are multiples of 4 via next() and remove()
StdOut.println("remove elements that are a multiple of 4 via next() and remove()");
while (iterator.hasNext()) {
int x = iterator.next();
if (x % 4 == 0) iterator.remove();
}
StdOut.println(list);
StdOut.println(); // remove all even elements via previous() and remove()
StdOut.println("remove elements that are even via previous() and remove()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
if (x % 2 == 0) iterator.remove();
}
StdOut.println(list);
StdOut.println(); // add elements via next() and add()
StdOut.println("add elements via next() and add()");
while (iterator.hasNext()) {
int x = iterator.next();
iterator.add(x + 1);
}
StdOut.println(list);
StdOut.println(); // add elements via previous() and add()
StdOut.println("add elements via previous() and add()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
iterator.add(x * 10);
iterator.previous();
}
StdOut.println(list);
StdOut.println();
}
}

算法Sedgewick第四版-第1章基础-021一双向链表,在遍历时可修改、删除元素的更多相关文章

  1. 算法Sedgewick第四版-第1章基础-001递归

    一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...

  2. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)

    一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...

  3. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)

    一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...

  4. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-006归并排序(Mergesort)

    一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursivel ...

  5. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版

    package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...

  6. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)

    一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...

  7. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)

    一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...

  8. 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的

    1. package algorithms.stacks13; /******************************************************************* ...

  9. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法

    1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...

随机推荐

  1. 实现多层抽屉菜单,点击其中一项会动画打开该抽屉--第三方开源--MultiCardMenu

    下载地址:https://github.com/wujingchao/MultiCardMenu <net.wujingchao.android.view.MultiCardMenu xmlns ...

  2. 20180831_jar包冲突2_天安微信httpclient冲突

    一.异常现象 微信项目需要向腾讯服务器发送请求获取token. 但是在请求的时候抛了个异常: <2018-8-30 下午05时39分18秒 CST> <Notice> < ...

  3. 网络编程基础--协程--greenlet切换---gevent自动识别 IO ---

    协程: 1 单线程来实现并发---协程: 协程:是单线程下的并发,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程, 即协程是由用户程序自己控制调度的 只 ...

  4. UVALive 3635 Pie(二分法)

    简单的二分法应用,循环1000次精度就满足要求了. #include<iostream> #include<cstdio> #include<cstdlib> #i ...

  5. python数据类型、操作符

    python中数据类型包含:int,float,boolean,string,list(列表),set(集合),dictionary(字典) 数据类型转换: ①字符串 转 int:>>&g ...

  6. 使用visio 2010建立sql server数据模型——手动画、利用逆向工程

    基础数据库这个词不在新鲜,老早就提出了.咱们从出生,个人信息就被放到一个基本信息库中了,在全国各地,通过身份证号就能知道你的基本信息.最近米老师 下发了一个任务,让我们开发几个小项目,考试系统.选修课 ...

  7. 已知一个数组a[N]来构造数组b[N]的有趣算法题

    给定一个数组a[N],我们希望构造数组b[N],其中b[i]=a[0]*a[1]*...*a[N-1]/a[i].在构造过程要求满足:1.不使用除法:2.O(1)空间复杂度和O(n)时间复杂度:3.除 ...

  8. 461. Hamming Distance Add to List

    // 快速法求1的个数 int BitCount2(unsigned int n) { unsigned ; ; n; ++c) { n &= (n -) ; // 清除最低位的1 } ret ...

  9. 使用python实现两个文件夹里文件的对比(包含内容的对比)

    #-*-coding:utf-8-*- #=============================================================================== ...

  10. 巧用padding让图片宽高比固定并自适应布局

    1.从上图知道原始图片大小是 800 * 250,即宽高比为 3.2: 2.html 及 css 代码如下, 可以知道就只是在一个div里面放了一张图片,那么如何让这张图片的宽高比固定呢,看了css之 ...