Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- class Node
- {
- private:
- int _id;
- std::string _name;
- public:
- Node(int id, std::string name)
- : nextNode(0), _id(id), _name(name)
- { }
- Node(Node* nextNode, int id, std::string name)
- : nextNode(nextNode), _id(id), _name(name)
- { }
- int getId() { return _id; }
- std::string getName() { return _name; }
- Node* nextNode;
- void print()
- {
- std::cout << getId() << " - " << getName() << std::endl;
- }
- };
- class List
- {
- private:
- Node* _first;
- public:
- void push(int id, std::string name);
- bool pushAfter(int targetId, int id, std::string name);
- bool remove(int targetId);
- bool swap(int targetId);
- bool print();
- List() : _first(0) { }
- ~List();
- };
- void List::push(int id, std::string name)
- {
- if (_first)
- {
- Node* node = new Node(_first, id, name);
- Node* curr = _first;
- while (curr->nextNode != _first)
- curr = curr->nextNode;
- curr->nextNode = node;
- }
- else
- {
- _first = new Node(id, name);
- _first->nextNode = _first;
- }
- }
- bool List::pushAfter(int targetId, int id, std::string name)
- {
- if (!_first)
- return false;
- Node* curr = _first;
- for (; curr->nextNode != _first && curr->getId() != targetId; curr = curr->nextNode);
- if (curr->getId() != targetId)
- return false;
- Node* node = new Node(curr->nextNode, id, name);
- curr->nextNode = node;
- return true;
- }
- bool List::remove(int targetId)
- {
- if (!_first)
- return false;
- Node* curr = _first;
- for (; curr->nextNode->getId() != targetId && curr->nextNode != _first; curr = curr->nextNode);
- if (curr->nextNode->getId() != targetId)
- return false;
- Node* next = curr->nextNode->nextNode;
- if (curr->nextNode == _first)
- _first = next;
- delete curr->nextNode;
- curr->nextNode = next;
- return true;
- }
- bool List::swap(int targetId)
- {
- if (!_first)
- return false;
- Node* curr = _first;
- for (; curr->nextNode->getId() != targetId && curr->nextNode != _first; curr = curr->nextNode);
- if (curr->nextNode->getId() != targetId)
- return false;
- Node* a = curr->nextNode;
- Node* b = a->nextNode;
- Node* c = b->nextNode;
- curr->nextNode = b;
- b->nextNode = a;
- a->nextNode = c;
- if (a == _first) _first = b;
- if (b == _first) _first = a;
- return true;
- }
- bool List::print()
- {
- if (!_first)
- return false;
- _first->print();
- for (Node* curr = _first->nextNode; curr != _first; curr = curr->nextNode)
- curr->print();
- return true;
- }
- List::~List()
- {
- Node* curr = _first;
- Node* next = 0;
- while (curr != _first && next)
- {
- next = curr->nextNode;
- delete curr;
- curr = next;
- }
- }
- int main()
- {
- List list;
- list.push(0, "a");
- list.push(1, "b");
- list.push(2, "c");
- list.push(3, "d");
- /* [0, 1, 2, 3] */
- list.remove(2);
- /* [0, 1, 3] */
- list.swap(1);
- /* [0, 3, 1] */
- list.print();
- return 0;
- }
Add Comment
Please, Sign In to add comment