-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathMyBag.java
More file actions
64 lines (52 loc) · 1.25 KB
/
MyBag.java
File metadata and controls
64 lines (52 loc) · 1.25 KB
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
package com.example;
import java.util.Iterator;
/**
* API<br>
* public class Bag<I> implements Iterable<T><br>
* Bag() 创建一个背包<br>
* void add(T item) 添加一个元素<br>
* boolean isEmpty() 背包是否为空<br>
* int size() 背包大小<br>
* Created by siyehua in 2016/12/10.
*/
public class MyBag<T> implements Iterable<T> {
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T> {
private Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T item = current.item;
current = current.next;
return item;
}
@Override
public void remove() {
}
}
private class Node {
Node next;
T item;
}
private Node first;
int size;
public void add(T item) {
Node node = new Node();
node.item = item;
node.next = first;
first = node;
size++;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
}