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. Win7 Nginx启动失败 cmd命令失败

    Win7  Nginx启动失败 cmd命令失败 Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服 ...

  2. python--pycharm汉化

    一.准备工具 1.pycharm软件 2.汉化包 二.解压汉化包 三.将resources_cn.jar复制到pycharm文件中lib目录下 四.重新打开pycharm

  3. "Cannot declare member function ...to have static linkage"错误

    英文解释: if you declare a method to be static in your .cc file. The reason is that static means somethi ...

  4. C语言中time函数获取系统时间

    可以通过time()函数来获得计算机系统当前的日历时间(Calendar Time),处理日期时间的函数都是以本函数的返回值为基础进行运算.其原型为: time_t time(time_t * t); ...

  5. C#获取路由器外网IP,MAC地址

    C#实现的获取路由器MAC地址,路由器外网地址.对于要获取路由器MAC地址,一定需要知道路由器web管理系统的用户名和密码.至于获取路由器的外网IP地址,可以不需要知道路由器web管理系统的用户名和密 ...

  6. Js里头的对象字面量

    JavaScript 对象字面量 在编程语言中,字面量是一种表示值的记法.例如,"Hello, World!" 在许多语言中都表示一个字符串字面量(string literal ) ...

  7. Python collections系列之双向队列

    双向队列(deque) 一个线程安全的双向队列 1.创建一个双向队列 import collections d = collections.deque() d.append(') d.appendle ...

  8. salt-minion dead but pid file exists 正确解决方法

    说明: 看了网上很多关于alt-minion dead but pid file exists 的解决方法,千篇一律的写一个shell脚本 killproc salt-minion 见链接:http: ...

  9. HDU5692(dfs序+线段树)

    Snacks Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submis ...

  10. Day2-VIM(四):修改

    字符替换 r 单个字符替换 R 连续替换 - 更改大小写 很简单,多试试就行了 tips:4-更改连续4个字符的大小写,很有意思 单词修改 cw 从光标处修改到单词结尾 cb 从光标处修改到单词开头 ...