-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBag.java
More file actions
50 lines (43 loc) · 1.24 KB
/
Bag.java
File metadata and controls
50 lines (43 loc) · 1.24 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
import java.util.Iterator;
public class Bag<Item> implements Iterable<Item>{
private int N=0;
private Node first;
private class Node{
Item item;
Node next;
}
public void add(Item item){
Node oldfirst=first;
first=new Node();
first.item=item;
first.next=oldfirst;
N++;
}
public int size(){return N;}
public boolean isEmpty(){return N==0;}
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;
}
}
public static void main(String[] args){
Bag<String> s =new Bag<String>();
for (int i=0;i<10;i++){
s.add(Integer.toString(i));
}
//System.out.println(s);
// for (int i=0;i<10;i++){
// System.out.println(s.pop());
// }
//s.delete(10);
for (String item:s){System.out.println(item + "");}
}
}