Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Stack
- {
- protected:
- const int maxSize = 6;
- int *elements;
- int top;
- public:
- Stack()
- {
- top = -1;
- elements = new int [maxSize];
- }
- Stack(const Stack &v)
- {
- top = v.top;
- elements = new int[maxSize];
- for (int i = 0; i < top; i++)
- elements[i] = v.elements[i];
- }
- virtual bool isFull()
- {
- return top+1>= maxSize;
- }
- bool isEmpty()
- {
- return top <= -1;
- }
- virtual void push(int value)
- {
- if (Stack::isFull())
- {
- cout << "Stack overflow" << endl;
- return;
- }
- elements[++top] = value;
- }
- virtual void pop()
- {
- if (isEmpty())
- {
- cout << "Stack is empty" << endl;
- return;
- }
- top--;
- }
- void show()
- {
- for (int i = 0; i <= top; i++)
- cout << elements[i] << " ";
- cout << endl;
- }
- };
- class Queue : public Stack
- {
- public:
- Queue() : Stack() {}
- Queue(const Queue &v) : Stack(v) {}
- virtual void push(int value)
- {
- if (isFull())
- {
- cout << "Queue is full" << endl;
- return;
- }
- Stack::push(value);
- }
- virtual void pop()
- {
- if (isEmpty())
- {
- cout << "Queue is empty" << endl;
- return;
- }
- for (int i = 0; i < top; i++)
- elements[i] = elements[i+1];
- top--;
- }
- };
- class RingBuffer : public Queue
- {
- int bottom;
- public:
- RingBuffer() : Queue()
- {
- bottom = 0;
- }
- RingBuffer(const RingBuffer &v) : Queue(v)
- {
- bottom = v.bottom;
- }
- void push(int value)
- {
- if (Stack::isFull())
- {
- elements[bottom] = value;
- bottom++;
- }
- else
- Stack::push(value);
- }
- void pop()
- {
- if (isEmpty())
- {
- cout << "Ring Buffer is empty" << endl;
- }
- else if (bottom<=top)
- {
- for (int i = bottom; i <maxSize-1; i++)
- elements[i] = elements[i+1];
- top--;
- }
- else
- Queue::pop();
- }
- };
- const int SIZE = 7;
- int main()
- {
- int m[SIZE] = { 5, 3, 6, 9, 3, 9 ,0};
- cout << "---Stack---" << endl;
- Stack stack;
- cout << "Init" << endl;
- for (int i = 0; i < SIZE; i++)
- stack.push(m[i]);
- stack.show();
- cout << "Pop 2 times" << endl;
- stack.pop();
- stack.pop();
- stack.show();
- cout << "---Queue---" << endl;
- Queue queue;
- cout << "Init" << endl;
- for (int i = 0; i < SIZE; i++)
- queue.push(m[i]);
- queue.show();
- cout << "Pop 2 times" << endl;
- queue.pop();
- queue.pop();
- queue.show();
- cout << "---Ring buffer---" << endl;
- RingBuffer ringBuffer;
- cout << "Init" << endl;
- for (int i = 0; i < SIZE-1; i++)
- ringBuffer.push(m[i]);
- ringBuffer.show();
- cout << "Push ";
- int n[4] = { 7,8, 2, 1 };
- for (int i = 0; i < 4; i++)
- cout << n[i] << " ";
- cout << endl;
- for (int i = 0; i < 4; i++)
- ringBuffer.push(n[i]);
- ringBuffer.show();
- cout << "Pop 3 times" << endl;
- ringBuffer.pop();
- ringBuffer.pop();
- ringBuffer.pop();
- ringBuffer.show();
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement