-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBag.java
54 lines (44 loc) · 1.14 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
import java.util.Iterator;
public class Bag<Item> implements Iterable<Item>
{
private Node first;
public class Node
{
public Item item;
public Node next;
}
public void add(Item x)
{
Node oldfirst = first;
first = new Node();
first.item = x;
first.next = oldfirst;
}
public class BagIterator implements Iterator<Item>
{
private Node x = first;
public Item next()
{
Item item = x.item;
x = x.next;
return item;
}
public boolean hasNext()
{ return x != null; }
}
public Iterator<Item> iterator()
{
return new BagIterator();
}
public static void main(String[] args)
{ // Read integers from StdIn.
Bag<Integer> b = new Bag<Integer>();
int[] ints = StdIn.readAllInts();
// Add integers to bag.
for (int i = 0; i < ints.length; i++)
{ b.add(i); }
// Iterate through bag, printing out integers.
StdOut.println("Here are the Integers in your Bag:");
for (int i : b) { StdOut.println(i); }
}
}