---- 21 Double ended
//---- By Base Method
#include <iostream>
#define MAX_SIZE 100
class Deque
{
private:
int arr[MAX_SIZE];
int front;
int rear;
public:
Deque()
{
front = -1;
rear = -1;
}
bool isEmpty()
{
return (front == -1 && rear == -1);
}
bool isFull()
{
return (rear + 1) % MAX_SIZE == front;
}
void pushFront(int data)
{
if (isFull()) {
std::cout << "Deque is full. Cannot push." <<
std::endl;
return;
} else if (isEmpty()) {
front = rear = 0;
} else {
front = (front - 1 + MAX_SIZE) % MAX_SIZE;
}
arr[front] = data;
}
void pushBack(int data) {
if (isFull()) {
std::cout << "Deque is full. Cannot push."
<< std::endl;
return;
} else if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX_SIZE;
}
arr[rear] = data;
}
int popFront() {
if (isEmpty()) {
std::cout << "Deque is empty. Cannot pop."
<< std::endl;
// Assuming -1 represents an error or empty deque
return -1;
} else if (front == rear) {
int data = arr[front];
front = rear = -1;
return data;
} else {
int data = arr[front];
front = (front + 1) % MAX_SIZE;
return data;
}
}
int popBack() {
if (isEmpty()) {
std::cout << "Deque is empty. Cannot pop."
<< std::endl;
// Assuming -1 represents an error or empty deque
return -1;
} else if (front == rear) {
int data = arr[rear];
front = rear = -1;
return data;
} else {
int data = arr[rear];
rear = (rear - 1 + MAX_SIZE) % MAX_SIZE;
return data;
}
}
};
int main() {
Deque deque;
deque.pushFront(1);
deque.pushFront(2);
deque.pushBack(3);
deque.pushBack(4);
std::cout << "Deque: ";
std::cout << deque.popFront() << " ";
std::cout << deque.popFront() << " ";
std::cout << deque.popBack() << " ";
std::cout << deque.popBack() << std::endl;
return 0;
}
//-----By SDL
#include <iostream>
#include <deque>
int main() {
// Creating a deque
std::deque<int> myDeque;
// Inserting elements at the front
myDeque.push_front(1);
myDeque.push_front(2);
// Inserting elements at the back
myDeque.push_back(3);
myDeque.push_back(4);
// Displaying the deque
std::cout << "Deque: ";
for (auto it = myDeque.begin(); it != myDeque.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Removing element from the front
myDeque.pop_front();
std::cout << "Popped Front: " << myDeque.front() << std::endl;
// Removing element from the back
myDeque.pop_back();
std::cout << "Popped Back: " << myDeque.back() << std::endl;
// Displaying the deque after popping
std::cout << "Deque after popping: ";
for (auto it = myDeque.begin(); it != myDeque.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
No comments:
Post a Comment
Fell free to write your query in comment. Your Comments will be fully encouraged.