-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathBag.java
110 lines (95 loc) · 2.62 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
package com.thealgorithms.datastructures.bags;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A collection that allows adding and iterating over elements but does not support element removal.
*
* @param <E> the type of elements in this bag
*/
public class Bag<E> implements Iterable<E> {
private Node<E> firstElement; // First element in the bag
private int size; // Number of elements in the bag
// Node class representing each element in the bag
private static final class Node<E> {
private E content;
private Node<E> nextElement;
}
/**
* Constructs an empty bag.
*/
public Bag() {
firstElement = null;
size = 0;
}
/**
* Checks if the bag is empty.
*
* @return true if the bag is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the number of elements in the bag.
*
* @return the number of elements
*/
public int size() {
return size;
}
/**
* Adds an element to the bag.
*
* @param element the element to add
*/
public void add(E element) {
Node<E> newNode = new Node<>();
newNode.content = element;
newNode.nextElement = firstElement;
firstElement = newNode;
size++;
}
/**
* Checks if the bag contains a specific element.
*
* @param element the element to check for
* @return true if the bag contains the element, false otherwise
*/
public boolean contains(E element) {
for (E value : this) {
if (value.equals(element)) {
return true;
}
}
return false;
}
/**
* Returns an iterator over the elements in this bag.
*
* @return an iterator that iterates over the elements in the bag
*/
@Override
public Iterator<E> iterator() {
return new ListIterator<>(firstElement);
}
// Private class for iterating over elements
private static class ListIterator<E> implements Iterator<E> {
private Node<E> currentElement;
ListIterator(Node<E> firstElement) {
this.currentElement = firstElement;
}
@Override
public boolean hasNext() {
return currentElement != null;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
}