-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
DoublyLinkedList.java
94 lines (74 loc) · 2.14 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
package ds;
import java.util.NoSuchElementException;
/**
* Created by sherxon on 2/25/17.
*/
public class DoublyLinkedList<E> {
int size;
private Node head; // the first element
private Node tail; // the last element
public void add(E element) {
if (element == null) throw new AssertionError();
// tail and head are the same node when list has only one item
if (head == null) {
head = tail = new Node(element);
} else {
//assign new node to next of tail and make tail the last element
tail.next = new Node(element, tail, null);
tail = tail.next;
}
size++;
}
public boolean isEmpty() {
return size == 0;
}
public int getSize() {
return size;
}
public E get(int index) {
if (index >= size && index < 0) // check boundaries
throw new NoSuchElementException();
// find element at given index
Node node = head;
for (int i = 0; i < index; i++)
node = node.next;
return node.elem;
}
public boolean delete(E element) {
Node temp = head;
while (temp != null && !temp.elem.equals(element)) {
temp = temp.next;
}
// no node with given element is found
if (temp == null) return false;
size--;
// if found node is head of the list, need to change to next element
if (temp == head) {
head = head.next;
return true;
}
// if found node is last node of the list, need to change tail
if (temp == tail) {
tail = temp.prev;
return true;
}
// change links
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
return true;
}
// wrapper class for list elements
private class Node {
E elem;
Node next;
Node prev;
public Node(E elem) {
this.elem = elem;
}
public Node(E elem, Node prev, Node next) {
this.elem = elem;
this.next = next;
this.prev = prev;
}
}
}