-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bag.java
37 lines (35 loc) · 1.01 KB
/
Bag.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package S4_Graphs.S4_1_Undirected_Graph.S4_1_2_Graph;
import java.util.Iterator;
/**
* Created by Brian Lee on 2018/9/4.
*/
public class Bag<Item> implements Iterable<Item> {
private class Node {
Item item;
Node next;
}
private Node first; //栈顶
private int N; //元素数量
public boolean isEmpty() { return N == 0; }
public int size() { return N; }
public void add(Item item) {
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
N ++;
}
public Iterator<Item> iterator() {
return new ListIterator();
}
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;
}
}
}