-
Notifications
You must be signed in to change notification settings - Fork 3
/
Bag.java
114 lines (94 loc) · 2.53 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package DataStructure;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Bag<Item> implements Iterable<Item> {
private Node first;
private int size;
private class Node {
private Node next;
private Item item;
}
/**
* Creates a empty container of objects, that can be
* extended without consideration. It provides an iterator
* over the values contained in this Bag.
*/
public Bag() {
size = 0;
first = null;
}
/**
* Creates a container of objects, initialized with the
* given items, that can be extended without
* consideration. It provides an iterator values
* contained in this Bag.
*/
public Bag(Iterable<Item> items) {
size = 0;
first = null;
for (Item item : items) {
add(item);
}
}
/**
* Creates a container of objects, initialized with the
* given items, that can be extended without
* consideration. It provides an iterator values
* contained in this Bag.
*/
public Bag(Bag bag) {
size = 0;
first = null;
Iterator<Item> iterator = bag.iterator();
while (iterator.hasNext()) {
Item next = iterator.next();
add(next);
}
}
/**
* Adds the item to the bag.
*
* @param item, the provided item.
*/
public void add(Item item) {
Node oldFirst = first;
first = new Node();
first.next = oldFirst;
first.item = item;
size++;
}
/**
* Return the size of the bag.
*/
public int size() {
return size;
}
/**
* Returns {@code true} if the queue is empty, otherwise, return {@code false}.
*/
public boolean isEmpty() {
return (size == 0);
}
/**
* Returns an iterator over the items contained in this bag.
* The items are iterated over in arbitrary order.
*/
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() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException("Empty bag.");
Item item = current.item;
current = current.next;
return item;
}
}
}