-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathCircularDeque.java
133 lines (110 loc) · 2.36 KB
/
CircularDeque.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
Solved By: Sandeep Ranjan (1641012352)
Solution for Programming Project
4.2
*/
class CirDeque {
private int max,rear,front, nEle;
private int[] a;
public CirDeque (int m) {
max = m;
a = new int[m];
rear = front = -1;
nEle = 0;
}
public boolean isFull() {
return ((front == 0 && rear == max-1)|| front == rear+1);
}
public boolean isEmpty () {
return (front == -1);
}
public void insertFront(int val) {
if (isFull()) {
System.out.println("Overflow as queue is Full");
} else {
if (rear == -1) {
front = rear = 0;
} else if (front == 0) {
front = max - 1;
}
else {
front--;
}
a[front] = val;
nEle++;
}
}
public void insertRear(int val) {
if (isFull()) {
System.out.println("Overflow as queue is Full");
} else {
if (front == -1) {
front = 0;
rear = 0;
} else if (rear == max-1) {
rear = 0;
} else {
rear++;
}
a[rear] = val;
nEle++;
}
}
public void deleteFront() {
if (isEmpty()) {
System.out.println("Queue Underflow");
} else {
if (front == rear) {
front = rear = -1;
} else {
if (front == max -1) {
front = 0;
} else {
front++;
}
}
nEle--;
}
}
public void deleteRear() {
if (isEmpty()) {
System.out.println(" Underflow");
return ;
} else {
if (front == rear) {
front = -1;
rear = -1;
} else if (rear == 0) {
rear = max-1;
} else {
rear = rear-1;
}
nEle--;
}
}
public void display() {
int j = front;
for(int i=0; i<nEle; i++) {
System.out.print(a[j] + " ");
j++;
if(j == max) {
j = 0;
}
}
System.out.println();
}
}
class CircularDeque {
public static void main(String[] args) {
CirDeque cD = new CirDeque(5);
cD.insertFront(10);
cD.insertFront(20);
cD.insertFront(30);
cD.display();
cD.insertRear(40);
cD.display();
cD.deleteRear();
cD.deleteFront();
cD.display();
}
}