void DLList::insert(int newValue) { if (head == NULL) pushFront(newValue); else if (newValue <= head->getContents()) pushFront(newValue); else if (newValue >= tail->getContents()) pushBack(newValue); else { DLNode* spot = head; while (spot->getNext() != NULL && newValue > spot->getContents()) spot = spot->getNext(); if (spot->getNext() == NULL && newValue >= spot->getContents()) pushBack(newValue); else { DLNode* newNode = new DLNode(newValue); DLNode* trailer = spot->getPrevious(); trailer->setNext(newNode); newNode->setNext(spot); newNode->setPrevious(trailer); spot->setPrevious(newNode); size++; } } }
//remove the first instance of a DLNode containing target; do nothing if target is not found bool DLList::removeFirst (int target) { if(head == NULL) { return false; } else if(head->getContents()==target) { popFront(); return true; } else { DLNode* temp = head; while(temp->getNext() != NULL) { DLNode* nextTemp = temp->getNext(); if(temp->getContents() == target) { temp->getPrevious()->setNext(nextTemp); nextTemp->setPrevious(temp->getPrevious()); delete temp; size--; if(size == 1) { head = tail; } return true; } temp = temp->getNext(); } if(temp->getContents() == target) { popBack(); return true; } return false; } }
bool DLList::removeFirst(string target) { if(head_node == NULL) { return false; } DLNode* temp = head_node; DLNode* previous = temp; if(head_node->getContents() == target) { cout << "Eliminated " << target << endl; popFront(); return true; } if(tail_node->getContents() == target) { cout << "Eliminated " << target << endl; popBack(); return true; } // There is no reason why this loop would be endless, so there won't be a catch. // The incoming TARGET string is only called when getStop finishes. while(temp->getContents() != target) { // Get next node and continue, and keep previous 1 behind. previous = temp; temp = temp->getNext(); } if(temp->getContents() == target) { cout << "Eliminated " << target << endl; // Delete Node // Setting previous' node to the next node of temp previous->setNext(temp->getNext()); // Setting temp's next node's PREVIOUS to temp's previous NODE temp->setPrevious(temp->getPrevious()); delete temp; temp = NULL; node_count--; return true; } else { cout << "RemoveFirst returned false entirely (bad?)"<<endl;return false;} }