-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericLinkedList.java
More file actions
119 lines (94 loc) · 2.31 KB
/
GenericLinkedList.java
File metadata and controls
119 lines (94 loc) · 2.31 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
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
115
116
117
118
119
package il.co.ilrd.genericlinkedlist;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
public class GenericLinkedList<T> implements Iterable<T> {
private Node head;
private int modCount;//fail-fast iterator var
public void pushFront(T data) {
head = new Node(data, head);
++modCount;
}
public T popFront() {
assert(null != head);
T poppedData = head.data;
head = head.next;
++modCount;
return (poppedData);
}
public long getSize(){
long counter = 0;
ListIterator iter = new ListIterator(head);
while (iter.hasNext()) {
++counter;
iter.next();
}
return (counter);
}
public boolean isEmpty(){
return (null == head);
}
public Iterator<T> getBegin() {
ListIterator iter = new ListIterator(head);
return (iter);
}
public Iterator<T> find(T toFind){
ListIterator iter = new ListIterator(head);
for(T t : this) {
if (toFind.equals(t))
{
return (iter);
}
iter.next();
}
return (iter);
}
public Iterator<T> iterator() {
return new ListIterator(head);
}
private class Node {
private T data;
private Node next;
private Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
private class ListIterator implements Iterator<T> {
private Node node;
private int expectedModCount;//fail fast iterator var
private ListIterator(Node node) {
this.node = node;
expectedModCount = modCount;
}
@Override
public boolean hasNext() {
return (null != this.node);
}
@Override
public T next() throws ConcurrentModificationException {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
T data = node.data;
node = node.next;
return (data);
}
}
public static <E> GenericLinkedList<E> newReverse(GenericLinkedList<E> list) {
GenericLinkedList<E> reversedList = new GenericLinkedList<E>();
for (E element : list) {
reversedList.pushFront(element);
}
return (reversedList);
}
public static <E> GenericLinkedList<E> merge(GenericLinkedList<E> list1, GenericLinkedList<E> list2){
GenericLinkedList<E> mergedList = new GenericLinkedList<E>();
for (E element : list2) {
mergedList.pushFront(element);
}
for (E element : list1) {
mergedList.pushFront(element);
}
return newReverse(mergedList);
}
}