-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBag.java
71 lines (53 loc) · 1.46 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Bag.java
import java.util.Iterator;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Bag<Item> implements Iterable<Item>
{
private Node first; // top of stack
private int N; // number of items
private class Node
{
Item item;
Node next;
}
public boolean isEmpty() { return first == null; }
public int size() { return N; }
public void add(Item item)
{ // add item to top of stack
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;
}
}
// test client
public static void main(String[] args)
{ // add items to bag and itterate them
Bag<String> b = new Bag<String>();
while (!StdIn.isEmpty())
{
String item = StdIn.readString();
b.add(item);
}
for (String item : b) {
StdOut.println(item);
}
StdOut.println("(" + b.size() + " items in bag)");
}
}