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. Swap Adjacent Elements

    You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this ...

  2. 「长乐集训 2017 Day1」区间 线段树

    题目 对于两个区间\((a,b),(c,d)\),若\(c < a < d\)或\(c < b < d\)则可以从\((a,b)\)走到\((c,d)\)去,现在有以下两种操作 ...

  3. hexo博客相关

    https://www.cnblogs.com/sulishibaobei/p/6428241.html 利用hexo+github+nodejs搭建自我博客的一天 http://www.sulish ...

  4. 页面报错Uncaught SyntaxError: Unexpected identifier

    错误描述:未捕获的语法错误:意想不到的标识符. 如图所示:检查之后发现是页面js内缺少“,”引起的.添加之后就OK了.

  5. C# 读xml注释或过滤xml注释

    有这么个需求: 要统计所有的配置文件,这些配置文件都xml格式,并把这些配置写到数据表里,如果有注释要把这些注释写到对应配置对象的描述字段上 <item id="" key= ...

  6. Angular5学习笔记 - 创建组件(四)

    一.创建组件 ng generate component component-name #简写 ng g c component-name ng generate directive|pipe|ser ...

  7. 编译PHP扩展的通用方法

    以安装swoole扩展为例: 步骤1: wget  pecl.php.net/get/swoole-1.7.21.tgz  (下载swoole打包文件) 步骤2: tar zxvf swoole-1. ...

  8. commandLink/commandButton/ajax backing bean action/listener method not invoked (转)

    Whenever an UICommand component fails to invoke the associated action method or an UIInputelement fa ...

  9. Jetty + Servlet 实现文件下载

    Jetty非常适合做嵌入式web开发,正如Jetty的口号"Don’t deploy your application in Jetty, deploy Jetty in your appl ...

  10. mysql查询最近30天、7天、每天、昨天、上个月的记录

      一些变量说明: add_time为插入的时间 to_days是sql函数,返回的是个天数 data_sub(date,INTERVAL expr type)给指定的日期减去多少天 data()函数 ...