-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathDoublyLinkedList.java
128 lines (105 loc) Β· 2.92 KB
/
DoublyLinkedList.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package LinkedList;
public class DoublyLinkedList<E> implements ILinkedList<E> {
private Node<E> header;
private Node<E> trailer;
private int size;
public DoublyLinkedList() {
header = new Node<>(null, null, null);
trailer = new Node<>(null, header, null);
header.setNext(trailer);
size = 0;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public E first() {
if (isEmpty()) return null;
return header.getNext().getElement();
}
@Override
public E last() {
if (isEmpty()) return null;
return trailer.getPrev().getElement();
}
@Override
public void addFirst(E e) {
addBetween(e, header, header.getNext());
}
@Override
public void addLast(E e) {
addBetween(e, trailer.getPrev(), trailer);
}
@Override
public E removeFirst() {
if (isEmpty()) return null;
return remove(header.getNext());
}
@Override
public E removeLast() {
if (isEmpty()) return null;
return remove(trailer.getPrev());
}
@Override
public String toString() {
if (isEmpty()) return "[]";
StringBuilder sb = new StringBuilder("[");
DoublyLinkedList.Node<E> current = header.getNext();
while (current.getNext() != trailer) {
sb.append(current.getElement()).append(", ");
current = current.getNext();
}
sb.append(current.getElement()).append("]");
return sb.toString();
}
private void addBetween(E e, Node<E> predecessor, Node<E> successor) {
Node<E> newest = new Node<>(e, predecessor, successor);
predecessor.setNext(newest);
successor.setPrev(newest);
size ++;
}
private E remove(Node<E> node) {
Node<E> predecessor = node.getPrev();
Node<E> successor = node.getNext();
predecessor.setNext(successor);
successor.setPrev(predecessor);
size --;
return node.getElement();
}
private static class Node<E> {
private E element;
private Node<E> prev;
private Node<E> next;
public Node() {
this(null, null, null);
}
public Node(E element, Node<E> prev, Node<E> next) {
this.element = element;
this.prev = prev;
this.next = next;
}
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getPrev() {
return prev;
}
public void setPrev(Node<E> prev) {
this.prev = prev;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
}