Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct cell
- {
- int value;
- cell* next;
- cell(int _value, cell* _next)
- {
- value = _value;
- next = _next;
- }
- };
- struct queue
- {
- cell* first;
- cell* last;
- size_t size;
- queue()
- {
- first = last = nullptr;
- size = 0;
- }
- bool isEmpty()
- {
- return first == nullptr;
- };
- void push(int value)
- {
- cell* newCell = new cell(value, nullptr);
- if (isEmpty())
- {
- first = last = newCell;
- }
- else
- {
- last->next = newCell;
- last = newCell;
- }
- size++;
- };
- int pop()
- {
- if (isEmpty())
- {
- throw exception("Queue is empty");
- }
- else if (first == last)
- {
- int toReturn = first->value;
- delete first;
- first = last = nullptr;
- size--;
- return toReturn;
- }
- else
- {
- int toReturn = first->value;
- cell* toDelete = first;
- first = first->next;
- delete toDelete;
- size--;
- return toReturn;
- }
- };
- void print()
- {
- if (isEmpty())
- {
- cout << "Queue is empty" << endl;
- return;
- }
- cell* tmp = first;
- size_t k = 1;
- while (tmp != nullptr)
- {
- cout << k++ << ") " << tmp->value << endl;
- tmp = tmp->next;
- }
- };
- void clear()
- {
- cell* tmp = first;
- while (tmp != nullptr)
- {
- cell* toDelete = tmp;
- tmp = tmp->next;
- delete toDelete;
- }
- first = last = nullptr;
- }
- int getById(size_t id)
- {
- if (id > size)
- throw exception("Out of size");
- cell* tmp = first;
- for (size_t k = 1; k < id; k++)
- tmp = tmp->next;
- return tmp->value;
- };
- };
- int main()
- {
- try
- {
- queue s;
- cout << endl << "1 test" << endl;
- s.print();
- cout << endl << "2 test" << endl;
- s.push(132);
- s.push(-32);
- s.push(112332);
- s.push(1122);
- s.print();
- cout << endl << "3 test" << endl;
- size_t amount;
- cout << "Enter the amount of elements you want to add: ";
- cin >> amount;
- for (size_t i = 0; i < amount; i++)
- {
- int value;
- cout << "Enter the value of [" << i + 1 << "] element = ";
- cin >> value;
- s.push(value);
- }
- s.print();
- }
- catch (exception ex)
- {
- cout << "Error: " << ex.what() << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment