文章目录
本博客代码示例均来自:算法 Algorithmes Forth Edition
[美] Robert Sedgewick Kevin Wayne 著 谢路云译
本篇博客介绍链表实现下压堆栈、FIFO及Bag. show you the code.
一、链表实现下压堆栈
package com.chm.algorithms.bagstackqueue;
import java.util.Iterator;
/**
* Author:meice Huang
* Time: 2020/3/8 上午12:53
* 算法1.2 下压堆栈(链表实现)
*/
public class Stack<Item> implements Iterable<Item> {
private Node first;//栈顶,最近添加的元素
private int N;//元素数量
private class Node {
Item item;
Node next;
}
public boolean isEmpty() {
return first == null;
}
;//或者N ==0
public int size() {
return N;
}
;
public void push(Item item) {
//向栈顶添加元素
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
N++;
}
public Item pop() {
//从栈顶删除元素
Item item = first.item;
first = first.next;
N--;
return item;
}
@Override
public Iterator<Item> iterator() {
return null;
}
}
二、链表实现FIFO
package com.chm.algorithms.bagstackqueue;
import java.util.Iterator;
/**
* Author:meice Huang
* Time: 2020/3/8 上午1:10
* 算法1.3 先进先出队列
*/
public class Queue<Item> implements Iterable<Item> {
private class Node {
Item item;
Node next;
}
private Node first;//指向最早添加的节点的连接
private Node last;//指向最近添加的节点的连接
private int N;//队列中元素数量
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void enqueue(Item item) {
//向表尾添加元素
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) {
first = last;
} else {
oldLast.next = last;
}
}
public Item dequeue() {
//从表头删除元素
Item item = first.item;
first = first.next;
if (isEmpty()) {
last = null;
}
N--;
return item;
}
@Override
public Iterator<Item> iterator() {
return null;
}
/**
* 1、first = first.next 非常好,只用变更顺序
*/
}
三、链表实现背包
package com.chm.algorithms.bagstackqueue;
import java.util.Iterator;
/**
* Author:meice Huang
* Time: 2020/3/8 上午1:27
*/
public class Bag<Item> implements Iterable<Item> {
private class Node {
Item item;
Node next;
}
private Node first;//链表的首节点
public void add(Item item) {
/**
* 我的实现
*/
/*
Node node = new Node();
node.item = item;
first.next = node;
*/
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
}
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {
}
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
@Override
public Iterator<Item> iterator() {
return null;
}
}
四、总结
书中的开发用例运行轨迹非常直观,便于理解。其实我喜欢这本书也是因为书本开始很多可视化的轨迹图,这些能让你很直观的感受到算法背后的复杂度。