-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDequeue.java
57 lines (46 loc) · 1.5 KB
/
Dequeue.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
package linear;
public class Dequeue {
DoublyLinkedList doublyLinkedList = new DoublyLinkedList(); // to achieve O(1) for all ops including removeLast which is O(n) in a SinglyLinkedList
int size = 0;
void insertFirst(int value){
doublyLinkedList.insertFirst(value);
size ++;
}
void insertLast(int value){
doublyLinkedList.insertLast(value);
size ++;
}
int removeFirst(){
if(isEmpty()) throw new EmptyDequeueException("Cannot remove an item from an empty Dequeue.");
int deletedNodeValue = doublyLinkedList.head.data;
doublyLinkedList.deleteFirst();
size--;
return deletedNodeValue;
}
int removeLast(){
if(isEmpty()) throw new EmptyDequeueException("Cannot remove an item from an empty Dequeue.");
int deletedNodeValue = doublyLinkedList.tail.data;
doublyLinkedList.deleteLast();
size--;
return deletedNodeValue;
}
int peekFirst(){
if(isEmpty()) throw new EmptyDequeueException("Cannot peek from an empty Dequeue.");
return doublyLinkedList.head.data;
}
int peekLast(){
if(isEmpty()) throw new EmptyDequeueException("Cannot peek from an empty Dequeue.");
return doublyLinkedList.tail.data;
}
boolean isEmpty(){
return size == 0;
}
int size(){
return size;
}
}
class EmptyDequeueException extends RuntimeException {
public EmptyDequeueException(String message) {
super(message);
}
}