-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDesignCircularDeque.java
102 lines (87 loc) · 2.38 KB
/
DesignCircularDeque.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
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.ListNode;
import java.util.Objects;
// https://leetcode.com/problems/design-circular-deque/
public class DesignCircularDeque {
private final int size;
private int actualSize;
private final ListNode head = new ListNode();
private ListNode tail;
public DesignCircularDeque(int size) {
this.size = size;
}
public boolean insertFront(int value) {
if (actualSize < size) {
ListNode newHead = new ListNode(value);
if (tail == null) {
tail = newHead;
head.next = tail;
tail.next = head;
} else {
newHead.next = head.next;
head.next = newHead;
}
actualSize++;
return true;
}
return false;
}
public boolean insertLast(int value) {
if (actualSize < size) {
ListNode newTail = new ListNode(value);
Objects.requireNonNullElse(tail, head).next = newTail;
newTail.next = head;
tail = newTail;
actualSize++;
return true;
}
return false;
}
public boolean deleteFront() {
if (actualSize != 0) {
head.next = head.next.next;
if (actualSize == 1) {
tail = null;
}
actualSize--;
return true;
}
return false;
}
public boolean deleteLast() {
if (actualSize != 0) {
if (actualSize == 1) {
head.next = null;
tail = null;
} else {
ListNode newTail = head.next;
while (newTail.next != tail) {
newTail = newTail.next;
}
newTail.next = head;
tail = newTail;
}
actualSize--;
return true;
}
return false;
}
public int getFront() {
if (actualSize != 0) {
return head.next.val;
}
return -1;
}
public int getRear() {
if (actualSize != 0) {
return tail.val;
}
return -1;
}
public boolean isEmpty() {
return actualSize == 0;
}
public boolean isFull() {
return actualSize == size;
}
}