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.
Python solution uses a list to simulate the circular deque operations. It utilizes the modulo operation to keep track of the indices effectively and allows wrap-around of front and rear. The solution checks if the deque is full or empty before insertions or deletions, respectively.
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).
1public class Node {
2 public int Value;
3 public Node Next;
4 public Node Prev;
5 public Node(int value) {
6 Value = value;
7 Next = Prev = null;
8 }
9}
10
11public class MyCircularDeque {
12 private Node front;
13 private Node rear;
14 private int size;
15 private int capacity;
16
17 public MyCircularDeque(int k) {
18 front = rear = null;
19 size = 0;
20 capacity = k;
21 }
22
23 public bool InsertFront(int value) {
24 if (IsFull()) return false;
25 Node node = new Node(value);
26 node.Next = front;
27 if (front != null) front.Prev = node;
28 front = node;
29 if (rear == null) rear = node;
30 size++;
31 return true;
32 }
33
34 public bool InsertLast(int value) {
35 if (IsFull()) return false;
36 Node node = new Node(value);
37 node.Prev = rear;
38 if (rear != null) rear.Next = node;
39 rear = node;
40 if (front == null) front = node;
41 size++;
42 return true;
43 }
44
45 public bool DeleteFront() {
46 if (IsEmpty()) return false;
47 front = front.Next;
48 if (front != null) front.Prev = null;
49 else rear = null;
50 size--;
51 return true;
52 }
53
54 public bool DeleteLast() {
55 if (IsEmpty()) return false;
56 rear = rear.Prev;
57 if (rear != null) rear.Next = null;
58 else front = null;
59 size--;
60 return true;
61 }
62
63 public int GetFront() {
64 return IsEmpty() ? -1 : front.Value;
65 }
66
67 public int GetRear() {
68 return IsEmpty() ? -1 : rear.Value;
69 }
70
71 public bool IsEmpty() {
72 return size == 0;
73 }
74
75 public bool IsFull() {
76 return size == capacity;
77 }
78}In C#, the linked list model for the deque supports dynamic sizing, letting each node connect bidirectionally, which allows rapid pointer modifications for diverse operations at both front and end.