List::List(const List &other): first(nullptr), last(nullptr), currentSize(0), def(0) { for (ListItem *item = other.first; item != nullptr; item = item->getNext()) { appendElement(item->getContent()); } }
List::List(const List& other): first(nullptr), last(nullptr), currentSize(0) { // Copy list item-wise to avoid having two lists pointing at the same list items for (ListItem *item = other.first; item != nullptr; item = item->getNext()) { appendElement(item->getContent()); } }
int& List::getNthElement(int n) { int index = n; ListItem* p = first; // iterate over elements while (index-- > 0) { p = p->getNext(); } return p->getContent(); }
int &List::getNthElement(int n) { if (currentSize >= n + 1 && n >= 0) { ListItem* tmp = first; for (int i = 0; i < n; i++) { tmp = tmp->getNext(); } return tmp->getContent(); } else throw std::out_of_range("List index out of range"); }
int List::deleteAt(int pos) { if (pos <= 0) return deleteFirst(); else if (pos >= getSize()) return deleteLast(); else { ListItem *del = first; while (pos-- > 0) { del = del->getNext(); } int val = del->getContent(); delete del; currentSize--; return val; } }
int List::deleteAt(int pos) { if (pos <= 0) { return deleteFirst(); } else if (pos >= currentSize - 1) { return deleteLast(); } else { int index = pos; ListItem* p = first; // iterate over elements while (index-- > 0) { p = p->getNext(); } int content = p->getContent(); delete p; --currentSize; return content; } }