-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
75 lines (74 loc) · 1.49 KB
/
Copy pathLinkedList.java
File metadata and controls
75 lines (74 loc) · 1.49 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
import java.util.Iterator;
public class LinkedList<T extends Comparable<T>> implements Iterable<T>{
private Node first, last;
private int size;
private class Node{
Node prev, next;
T item;
Node(T item){
this.item = item;
}
}
public int size(){
return size;
}
public void moveToFront(T item){
if(size == 0){
first = new Node(item);
last = first;
size++;
return;
}
Node foundNode = find(item);
if(foundNode != null && foundNode != first){
if(foundNode == last){
last.prev.next = null;
last = last.prev;
foundNode.next = first;
first.prev = foundNode;
foundNode.prev = null;
first = foundNode;
}
else{
foundNode.prev.next = foundNode.next;
foundNode.next.prev = foundNode.prev;
foundNode.prev = null;
foundNode.next = first;
first.prev = foundNode;
first = foundNode;
}
size++;
}
else if(foundNode == null){
Node newFirst = new Node(item);
newFirst.next = first;
first.prev = newFirst;
first = newFirst;
size++;
}
}
private Node find(T item){
Node curNode = first;
while(curNode != null){
if(curNode.item.compareTo(item) == 0){
return curNode;
}
curNode = curNode.next;
}
return null;
}
public Iterator<T> iterator() {
return new LLIterator();
}
private class LLIterator implements Iterator<T>{
Node curNode = first;
public boolean hasNext() {
return curNode != null;
}
public T next() {
T ret = curNode.item;
curNode = curNode.next;
return ret;
}
}
}