-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.java
98 lines (82 loc) · 2 KB
/
LinkedList.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
public class LinkedList <T> implements List<T> {
// ---------------------- fields ----------------------
private Link<T> first;
private Link<T> last;
// ---------------------- constructors ----------------------
public LinkedList(){
first = null;
last = null;
}
// ---------------------- methods ----------------------
//Returns true if this list contains no elements.
public boolean isEmpty() {
return first == null;
}
//Removes first element of this list
public T remove() {
Link<T> current = first;
if(current==null) throw new NullPointerException();
T ans = (T) current.getData();
first = first.getNext();
if(first!=null)
first.setPrev(null);
else
last = null;
return ans;
}
//Appends the specified element to the end of this list
public Link<T> add(T element) {
if(element == null)
throw new NullPointerException();
Link<T> newLink = new Link<>(element);
if(isEmpty()){
first = newLink;
last = newLink;
}
else {
last.setNext(newLink);
newLink.setPrev(last);
last = newLink;
}
return newLink;
}
public static class Link <E>{
// ---------------------- fields ----------------------
private E data;
private Link<E> next;
private Link<E> prev;
// ---------------------- constructors ----------------------
public Link(E data, Link<E> next,Link<E> prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
public Link(E data) {
this(data, null,null);
}
// ---------------------- Methods ----------------------
public Link<E> getNext() {
return next;
}
public Link<E> getPrev() {
return prev;
}
public void setNext(Link<E> next){
this.next = next;
}
public void setPrev(Link<E> prev){
this.prev = prev;
}
public E getData() {
return data;
}
public E setData(E data) {
E tmp = this.data;
this.data = data;
return tmp;
}
public String toString() {
return data.toString();
}
}
}