diff --git a/lab10/05.cpp b/lab10/05.cpp new file mode 100644 index 0000000..2c93396 --- /dev/null +++ b/lab10/05.cpp @@ -0,0 +1,169 @@ +#include +using namespace std; + +class Item { +public: + Item(int val) { + this->val = val; + this->prev = NULL; + this->next = NULL; + } + + int val; + Item* prev; + Item* next; +}; + +class List { +private: + Item* first; + Item* last; + int _size; +public: + List() { + first = NULL; + last = NULL; + _size = 0; + } + void push_back(int val) { + _size++; + if(last == NULL) { + Item* i = new Item(val); + first = i; + last = i; + return; + } + + Item* i = new Item(val); + last->next = i; + i->prev = last; + last = i; + } + Item* begin() { + return first; + } + Item* end() { + return last; + } + Item* find(int val) { + for(Item* i = begin(); i != NULL; i = i->next) { + if(i->val == val) { + return i; + } + } + return NULL; + } + bool erase(int pos) { + if(pos >= size()){ + return false; + } + + Item* i = begin(); + for(int counter = 1; counter <= pos; counter++) { + i = i->next; + } + + i->prev->next = i->next; + i->next->prev = i->prev; + + delete i; + _size--; + return true; + } + int size() { + return _size; + } + bool swap(int pos) { + // swap pos with the next + if(pos >= size()-1){ + return false; + } + + Item* a = begin(); + for(int counter = 1; counter <= pos; counter++) { + a = a->next; + } + Item* b = a->next; + + Item* before = a->prev; + Item* after = b->next; + + if(before) { + before->next = b; + } + else { + first = b; + } + + a->next = after; + a->prev = b; + b->next = a; + b->prev = before; + + if(after) { + after->prev = a; + } + else { + last = a; + } + + return true; + } +}; + +void printList(List* v) { + for(Item* i = v->begin(); i; i = i->next) { + cout<val<<" "; + } + cout<end(); i; i = i->prev) { + cout<val<<" "; + } + cout<prev->val<<" | Current: "<val<<" | After: "<next->val<