背包, 栈, 队列和线性表
背包
背包是最简单的数据结构, 只有添加数据和遍历元素两个功能, 内部实现是链表.
Bag.java
/******************************************************************************
* Compilation: javac Bag.java
* Execution: java Bag
* Author: Chenghao Wang
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Bag<T> implements Iterable<T> {
private class Node {
private T item;
private Node next;
Node(T item) {
this.item = item;
next = null;
}
}
private class BagIterator implements Iterator<T> {
private Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
if (current == null) throw new NoSuchElementException();
T result = current.item;
current = current.next;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private Node head = null;
public void add(T item) {
Node n = new Node(item);
n.next = head;
head = n;
}
@Override
public Iterator<T> iterator() {
return new BagIterator();
}
}
复杂度分析
- add: O(1)
栈
栈支持的功能有压栈, 出栈, 查询栈顶元素, 检查是否为空和查询元素个数. 内部实现也是链表.
Stack.java
/******************************************************************************
* Compilation: javac Stack.java
* Execution: java Stack
* Author: Chenghao Wang
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Stack<T> implements Iterable<T> {
private class Node {
private T item;
private Node next;
Node(T item) {
this.item = item;
next = null;
}
}