Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- template <class T>
- class Node
- {
- public:
- T data;
- Node* next;
- };
- template <class T>
- class Set
- {
- private:
- Node<T> *head;
- int size;
- public:
- Set()
- {
- this->head = nullptr;
- this->size = 0;
- }
- int getSize() const
- {
- return this->size;
- }
- void addElement(T el)
- {
- if (!this->containsElement(el))
- {
- Node<T> *node = new Node<T>();
- node->data = el;
- node->next = this->head;
- this->head = node;
- this->size++;
- }
- }
- void removeElement(T el)
- {
- Node<T> *current = head;
- Node<T> *prev = current;
- while (current != nullptr)
- {
- if (current->data == el)
- {
- prev->next = current->next;
- delete current;
- this->size--;
- return;
- }
- prev = current;
- current = current->next;
- }
- }
- bool containsElement(T el)
- {
- Node<T> *current = head;
- while (current != nullptr)
- {
- if (current->data == el)
- {
- return true; // element exists
- }
- current = current->next;
- }
- return false;
- }
- Set<T> unionSets(Set<T>& other)
- {
- Set<T> result;
- Node<T> *current = this->head;
- while (current != nullptr)
- {
- result.addElement(current->data);
- current = current->next;
- }
- current = other.head;
- while (current != nullptr)
- {
- result.addElement(current->data);
- current = current->next;
- }
- return result;
- }
- Set<T> intersectSets(Set<T>& other)
- {
- Set<T> result;
- Node<T> *current = this->head;
- while (current != nullptr)
- {
- if (other.containsElement(current->data))
- {
- result.addElement(current->data);
- }
- current = current->next;
- }
- return result;
- }
- void printElements()
- {
- Node<T> *current = this->head;
- while (current != nullptr)
- {
- cout << current->data << " ";
- current = current->next;
- }
- cout << endl;
- }
- };
- int main()
- {
- Set<int> s1, s2, s3;
- s1.addElement(1);
- s1.addElement(2);
- s1.addElement(3);
- s2.addElement(3);
- s2.addElement(4);
- s2.addElement(5);
- s1.printElements();
- s2.printElements();
- s3 = s1.intersectSets(s2);
- s3.printElements();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement