Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Problema 8, 10p
- #include <iostream>
- class Deque {
- private:
- int* data;
- int capacity;
- int front;
- int back;
- int count;
- void redimensioneaza() {
- int new_capacity = capacity * 2;
- int* new_data = new int[new_capacity];
- for (int i = 0; i < count; ++i) {
- new_data[i] = data[(front + i) % capacity];
- }
- delete[] data;
- data = new_data;
- capacity = new_capacity;
- front = 0;
- back = count;
- }
- public:
- Deque(int initial_capacity = 4) {
- capacity = initial_capacity;
- data = new int[capacity];
- front = 0;
- back = 0;
- count = 0;
- }
- ~Deque() {
- delete[] data;
- }
- void adauga_sfarsit(int value) {
- if (count == capacity) {
- redimensioneaza();
- }
- data[back] = value;
- back = (back + 1) % capacity;
- count++;
- }
- void adauga_inceput(int value) {
- if (count == capacity) {
- redimensioneaza();
- }
- front = (front - 1 + capacity) % capacity;
- data[front] = value;
- count++;
- }
- void scoate_sfarsit() {
- if (count == 0) return;
- back = (back - 1 + capacity) % capacity;
- count--;
- }
- void scoate_inceput() {
- if (count == 0) return;
- front = (front + 1) % capacity;
- count--;
- }
- int marime() {
- return count;
- }
- bool e_gol() {
- return count == 0;
- }
- int la_pozitie(int index) {
- if (index < 0 || index >= count) return -1;
- return data[(front + index) % capacity];
- }
- void insereaza(int index, int value) {
- if (index < 0 || index > count) return;
- if (count == capacity) {
- redimensioneaza();
- }
- if (index < count / 2) {
- front = (front - 1 + capacity) % capacity;
- for (int i = 0; i < index; ++i) {
- data[(front + i) % capacity] = data[(front + i + 1) % capacity];
- }
- data[(front + index) % capacity] = value;
- } else {
- for (int i = count; i > index; --i) {
- data[(front + i) % capacity] = data[(front + i - 1) % capacity];
- }
- data[(front + index) % capacity] = value;
- back = (back + 1) % capacity;
- }
- count++;
- }
- void sterge(int index) {
- if (index < 0 || index >= count) return;
- if (index < count / 2) {
- for (int i = index; i > 0; --i) {
- data[(front + i) % capacity] = data[(front + i - 1) % capacity];
- }
- front = (front + 1) % capacity;
- } else {
- for (int i = index; i < count - 1; ++i) {
- data[(front + i) % capacity] = data[(front + i + 1) % capacity];
- }
- back = (back - 1 + capacity) % capacity;
- }
- count--;
- }
- };
- int main() {
- Deque d;
- d.adauga_sfarsit(10);
- d.adauga_inceput(20);
- d.adauga_sfarsit(30);
- std::cout << "la_pozitie(0): " << d.la_pozitie(0) << "\n";
- std::cout << "la_pozitie(1): " << d.la_pozitie(1) << "\n";
- std::cout << "la_pozitie(2): " << d.la_pozitie(2) << "\n";
- d.insereaza(1, 99);
- std::cout << "dupa insereaza la 1: " << d.la_pozitie(1) << "\n";
- d.sterge(2);
- std::cout << "dupa sterge la 2: " << d.la_pozitie(2) << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement