Sponsored
Sponsored
This approach involves using a fixed-size array to represent the deque. We'll maintain two indices, front
and rear
, to manage the current front and last positions in the deque. Operations like insertions and deletions are performed by adjusting these indices while ensuring they wrap around using the modulo operation as necessary to remain within the array bounds.
Time Complexity: O(1) for each operation.
Space Complexity: O(k), where k is the capacity of the deque.
The Java solution uses an array and manages the front
and rear
indices to perform the required deque operations. It checks for both capacity and current size to determine the ability to insert or delete elements.
This approach makes use of a doubly linked list to implement the deque. This is particularly effective because it offers dynamic memory usage which can grow or shrink with the number of elements, instead of relying on a pre-allocated fixed-size structure as with arrays.
Time Complexity: O(1) for all operations.
Space Complexity: O(n), where n is the number of elements currently in the deque (potentially more efficient if n is much less than the initial capacity).
1#include <algorithm>
2using namespace std;
3
4class Node {
5public:
6 int value;
7 Node* next;
8 Node* prev;
9 Node(int value): value(value), next(nullptr), prev(nullptr) {}
10};
11
12class MyCircularDeque {
13 Node* front;
14 Node* rear;
15 int size;
16 int capacity;
17
18public:
19 MyCircularDeque(int k): size(0), capacity(k), front(nullptr), rear(nullptr) {}
20
21 bool insertFront(int value) {
22 if (isFull()) return false;
23 Node* node = new Node(value);
24 node->next = front;
25 if (front != nullptr) front->prev = node;
26 front = node;
27 if (rear == nullptr) rear = node;
28 size++;
29 return true;
30 }
31
32 bool insertLast(int value) {
33 if (isFull()) return false;
34 Node* node = new Node(value);
35 node->prev = rear;
36 if (rear != nullptr) rear->next = node;
37 rear = node;
38 if (front == nullptr) front = node;
39 size++;
40 return true;
41 }
42
43 bool deleteFront() {
44 if (isEmpty()) return false;
45 Node* temp = front;
46 front = front->next;
47 if (front != nullptr) front->prev = nullptr;
48 else rear = nullptr;
49 delete temp;
50 size--;
51 return true;
52 }
53
54 bool deleteLast() {
55 if (isEmpty()) return false;
56 Node* temp = rear;
57 rear = rear->prev;
58 if (rear != nullptr) rear->next = nullptr;
59 else front = nullptr;
60 delete temp;
61 size--;
62 return true;
63 }
64
65 int getFront() {
66 return isEmpty() ? -1 : front->value;
67 }
68
69 int getRear() {
70 return isEmpty() ? -1 : rear->value;
71 }
72
73 bool isEmpty() {
74 return size == 0;
75 }
76
77 bool isFull() {
78 return size == capacity;
79 }
80};
The C++ implementation uses a doubly linked list, making it flexible in memory usage. Each operation—whether insertion or deletion—adjusts pointers accordingly, ensuring seamless front or rear element manipulation.