Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- using namespace std;
- struct cell
- {
- char symbol;
- size_t amount;
- cell* next;
- cell(char symbol) : symbol(symbol), next(nullptr)
- {
- amount = 1;
- }
- cell(char symbol, size_t amount) : symbol(symbol), amount(amount),next(nullptr)
- {
- }
- };
- class queue
- {
- private:
- cell* first;
- cell* last;
- size_t size;
- public:
- queue() : first(nullptr), last(nullptr), size(0) {};
- bool isEmpty() { return size == 0; }
- void push(char symbol);
- cell pop();
- void sortByAmount();
- cell getById(size_t id);
- friend void print(const queue my);
- };
- void print(queue my)
- {
- if(my.isEmpty())
- {
- cout << "Queue is empty" << endl;
- return;
- }
- size_t counter = 1;
- cell* it = my.first;
- while(it!= nullptr)
- {
- cout << counter++ << ") Symbol = " << it->symbol << " | Amount = " << it->amount << endl;
- it = it->next;
- }
- };
- void fillFromFile(queue& my, const char* fileName)
- {
- ifstream input(fileName);
- if (!input.is_open())
- {
- cout << "File is not open" << endl;
- return;
- }
- char temp;
- while (!input.eof())
- {
- input >> temp;
- my.push(temp);
- }
- input.close();
- }
- int main()
- {
- queue a;
- cout << "Before adding" << endl;
- print(a);
- fillFromFile(a, "file.txt");
- cout << "After adding" << endl;
- print(a);
- cout << endl;
- cell save = a.getById(4);
- cout << "I got = " << save.symbol << endl << " amount = " << save.amount << endl;
- cout << "After adding" << endl;
- print(a);
- return 0;
- }
- void
- queue::push(char symbol)
- {
- if(isEmpty())
- {
- cell* newCell = new cell(symbol);
- first = last = newCell;
- size++;
- return;
- }
- cell* it = first;
- while (it != nullptr)
- {
- if (it->symbol == symbol)
- {
- it->amount++;
- return;
- }
- it = it->next;
- }
- cell* newCell = new cell(symbol);
- last->next = newCell;
- last = newCell;
- size++;
- }
- cell
- queue::pop()
- {
- if(isEmpty())
- {
- cout << "Error: Queue is empty " << endl;
- return '-';
- }
- if(first != last)
- {
- cell toReturn(first->symbol,first->amount);
- cell* toDelete = first;
- first = first->next;
- delete toDelete;
- size--;
- return toReturn;
- }
- else
- {
- cell toReturn(first->symbol, first->amount);
- delete first;
- first = last = nullptr;
- size--;
- return toReturn;
- }
- }
- cell
- queue::getById(size_t id)
- {
- if(isEmpty() | id > size)
- {
- cout << "Out of range" << endl;
- return cell('-');
- }
- cell* it = first;
- for(size_t i = 0 ;i < id; i++)
- {
- it = it-> next;
- }
- return cell(it->symbol, it->amount);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement