DLList<T>::DLList(const DLList<T> &listToCopy) { numItems = listToCopy.numItems; //if empty list if (listToCopy.firstNode == NULL) { firstNode = NULL; return; } Node<T>* rhs = listToCopy.firstNode; Node<T>* trav = new Node<T>; trav->setData(rhs->getData()); firstNode = trav; rhs = rhs->getNext(); while (rhs != NULL) { trav->setNext(new Node<T>); trav->getNext()->setPrevious(trav); trav = trav->getNext(); trav->setData(rhs->getData()); rhs = rhs->getNext(); } }
DLList<T>& DLList<T>::operator = (const DLList<T> &rightSide) { if (this == &rightSide) return *this; else { numItems = rightSide.numItems; this->~DLList<T>(); // delete old list if (rightSide.firstNode == NULL) // if rightSide is empty, done here. return *this; else // traverse rightSide and copy its Nodes to calling object. { Node<T>* rhs = rightSide.firstNode; Node<T>* trav = new Node<T>; trav->setData(rhs->getData()); // assign first node data firstNode = trav; // firstNode is now set. Doesnt change after this rhs = rhs->getNext(); while (rhs != NULL) { trav->setNext(new Node<T>); trav->getNext()->setPrevious(trav); trav = trav->getNext(); trav->setData(rhs->getData()); rhs = rhs->getNext(); } } return *this; } }
void EnhancedLinkedList<T>::remove_first(const T& key) { if (head != NULL) { if (head->getData() == key) { pop_front(); return; } Node<T> *current = head; Node<T> *previous = head; while (current != NULL) { if (current->getData() == key) { if (current->getData() == key) { pop_front(); return; } else { previous->getNext() = current->getNext(); delete current; count--; current = previous->getNext(); return; } } else { previous = current; current = current->getNext(); } } if (tail->getData() == key) { pop_back(); } } }
Queue<T>& Queue<T>::operator =(const Queue<T>& rightSide) { if (front == rightSide.front)//if the queues are the same return *this; else { //send left side back to freestore T next; while (! isEmpty( )) next = remove( );//remove calls delete. } if (rightSide.isEmpty( )) { front = back = NULL; return *this; } else { Node<T> *temp = rightSide.front;//temp moves //through the nodes from front to back of rightSide. back = new Node<T>(temp->getData( ), NULL); front = back; //First node created and filled with data. //New nodes are now added AFTER this first node. temp = temp->getLink( );//temp now points to second //node or NULL if there is no second node. while (temp != NULL) { back->setLink( new Node<T>(temp->getData( ), NULL)); back = back->getLink( ); temp = temp->getLink( ); } //back->link == NULL; return *this; } }
void WaterFaker::postStepProc(FEMUtil &femUtil, NodeHandler &nodeHandler, TimeHandler &timeHandler) { for (int i = 0; i < nodeHandler.getNodeNum(); i++) { Node* current = nodeHandler.getNode(i); float dt = timeHandler.getDeltaTime() / current->getData(MASSI); current->move(current->getData(MXI) * dt, current->getData(MYI) * dt, 0); // current->getData(MZI) * dt); float x = current->getX(); float y = current->getY(); if (isnan(x) || isnan(y)) { printf("NANTIME!!\n"); exit(1); } if (x < WALL_MINX) { current->setData(MXI, -current->getData(MXI) * .9f); current->setX(WALL_MINX); } else if (x > WALL_MAXX) { current->setData(MXI, -current->getData(MXI) * .9f); current->setX(WALL_MAXX); } if (y < WALL_MINY) { current->setData(MYI, 0); current->setY(WALL_MINY); } else if (y > WALL_MAXY) { current->setData(MYI, 0); current->setY(WALL_MAXY); } } }
void Graph::bfs(int start) { Queue<int> q(100); bool visited[SIZE]={false}; q.enqueue(start); visited[start] = true; std::cout<<std::endl; std::cout<<"BFS "<<std::endl; std::cout<< start << " "; while(!q.isEmpty()) { Node<int> *curr = array[q.dequeue()].gethead(); while(curr!=NULL) { if(!visited[curr->getData()]) { visited[curr->getData()] = true; q.enqueue(curr->getData()); std::cout<< curr->getData() << " "; } curr = curr->getNext(); } } }
Queue<T>::Queue(const Queue<T>& aQueue) { if (aQueue.isEmpty( )) front = back = NULL; else { Node<T> *temp = aQueue.front;//temp moves //through the nodes from front to back of aQueue. back = new Node<T>(temp->getData( ), NULL); front = back; //First node created and filled with data. //New nodes are now added AFTER this first node. temp = temp->getLink( );//temp now points to second //node or NULL if there is no second node. while (temp != NULL) { back->setLink(new Node<T>(temp->getData( ), NULL)); back = back->getLink( ); temp = temp->getLink( ); } //back->link == NULL } }
Queue<T> :: Queue(const Queue<T>& aQueue) { if ( aQueue.isEmpty() ) front = back = NULL; else { Node<T>* tmp = aQueue.front; //tmp moves through the node from front to back of aQueue back = new Node<T>(tmp->getData(), NULL); front = back; tmp = tmp->getLink(); //tmp now points to second node or NULL if there is no second node while(tmp != NULL) { back->setLink( new Node<T>(tmp->getData(), NULL) ); back = back->getLink(); tmp = tmp->getLink(); } //back->link == NULL } }
int main (int argc, char** argv) { using namespace std; int c = 1; // create a new list made by 1,2,3 Node start (c); Node *second=new Node(2);//new node to add start.append(second); Node *third=new Node(3);//new node to add start.append(third); //start.print (); //test on getPrevious //returns a pointer to the second node that stores value 2 Node *prec; prec=third->getPrevious() ; //test on getNext //returns a pointer to the second node that stores value 2 Node *succ; succ=start.getNext() ; //I check the value stored in the Node pointers to verify that getNext and getPrevious points to the correct node fprintf(stdout,"%d and %d",prec->getData(),succ->getData()); return 0; }
/************************************************************************ * Copy Constructor for List class ************************************************************************/ ListNum::ListNum(const ListNum &listToCopy) { Node* currentNode = listToCopy.firstNode; Node* copyNode; Node* newNodePrev; numItems = listToCopy.numItems; if (numItems == 0) { firstNode = NULL; lastNode = NULL; } else { firstNode = new Node(currentNode->getData()); lastNode = firstNode; currentNode = currentNode->getNext(); while (currentNode != NULL) { lastNode->setNext(new Node(currentNode->getData())); newNodePrev = lastNode; lastNode = lastNode->getNext(); lastNode->setPrevious(newNodePrev); currentNode = currentNode->getNext(); } } }
/*********************************************************************** * Overloaded assignment operator for list class. ***********************************************************************/ ListNum& ListNum::operator = (const ListNum &rightSide) { if (this != &rightSide) { Node* tempPtr = firstNode; while (firstNode != NULL) { tempPtr = firstNode->getNext(); delete firstNode; firstNode = tempPtr; } tempPtr = rightSide.firstNode; if (tempPtr != NULL) { firstNode = new Node(tempPtr->getData()); tempPtr = tempPtr->getNext(); } Node* prevThisList = firstNode; while (tempPtr != NULL) { lastNode->setNext(new Node (tempPtr->getData())); lastNode = lastNode->getNext(); lastNode->setPrevious(prevThisList); prevThisList = lastNode; tempPtr = tempPtr->getNext(); } numItems = rightSide.numItems; } return *this; }
int main() { Controller *master = new Controller(); cout << master->getList()->getSize()<<endl; for(int i = 0;i<50;i++){ master->generate(); } Node<Warrior> *temp = master->getList()->getFront(); while(temp!=0) { Soldier *s = dynamic_cast<Soldier*>(temp->getData()); if(s!=0) cout<<"Soldier!"<< s->getStrength()<<endl; Timmy *t = dynamic_cast<Timmy*>(temp->getData()); if(t!=0) cout<<"Timmy"<< t->getStrength()<<endl; Pirate *p = dynamic_cast<Pirate*>(temp->getData()); if(p!=0) cout<<"Pirate!"<< p->getStrength()<<endl; King *k = dynamic_cast<King*>(temp->getData()); if(k!=0) cout<<"King!"<< k->getStrength()<<endl; Harold *h = dynamic_cast<Harold*>(temp->getData()); if(h!=0) cout<<"Harold!"<< h->getStrength() <<endl; temp = temp->getNext(); } cout << master->getList()->getSize()<<endl; return 0; }
void view(){ Node *tmp = head; if(tmp == NULL){ cout << "Empty List " << endl; return; } else if(tmp->getNext() == NULL){ cout << tmp->getData(); cout << " --> "; cout << "NULL" << endl; } else{ do{ cout << tmp->getData(); cout << " --> "; tmp = tmp->getNext(); }while(tmp != NULL); cout << "NULL" << endl; } }
Node* insert(Node* head, int data){ Node* curr = head; Node* newNode = new Node(data); //handle head case if(newNode->getData() <= head->getData()){ //newNode set to head node newNode->setNext(head); //head now newNode head = newNode; }else{ //Find first node > newnode while(newNode->getData() > curr->getData()){ //iterate list curr = curr->getNext(); } //set newNode to next newNode->setNext(curr->getNext()); //set node before newnode to newnode curr->setNext(newNode); } return head; }
/** * Performs: * -# Data comparison between two Prime-Fibonacci extraction lists * -# aggregation of comparison results * -# output of those results in pre-defined format * * @param tExtract Prime-Fibonacci extraction of the target file. * "Target" is the file to be compared against. * @param outSS output stringstream from the outside world. ComparePF() * passes this on to the Nodes to modify and format the output * @return decimal representation of percentage similarity */ double CompareList::comparePF(CompareList& tExtract, stringstream& outSS) { // only need to compare the common section int size = (getSize() < tExtract.getSize()) ? (getSize()) : (tExtract.getSize()); // preparation int similarityCount = 0; Node * pCurrent = head; Node * tCurrent = tExtract.head; bool * similar = new bool[10]; for (int i = 0; i < 10; i++) similar[i] = false; // compare and collect results for(int i = 0; i < size; i++) { // compare nodes if(pCurrent->getData() == tCurrent->getData()) { similarityCount++; similar[i] = true; } pCurrent = pCurrent->getNext(); tCurrent = tCurrent->getNext(); } // output: // printing the PF bytes for target file and the prospect file // as well as some remarks getPFCompareResults(tExtract, similar, size, outSS); // clean up helper variables delete[] similar; return (size > 0) ? ((double) similarityCount/size) : (0); }
//adds new node into list //sorts by name void addOrdered(Type data){ Node<Type>* newNode = new Node<Type>(data); if(size == 0){ head = newNode; size++; }else{ Node<Type>* curr = head; Node<Type>* prev = nullptr; for(int i = 0; i < size; i++){ if(newNode->getData() < curr->getData()){ break; }else{ prev = curr; curr = curr -> getNext(); } } if(prev == nullptr) { head = newNode; } else { prev -> setNext(newNode); } newNode->setNext(curr); size++; } }
bool LinkedList::remove(int customerNumber) { if(isEmpty()) return false; Node* curr = this->head->getNext(); Node* prev = this->head; for(int i = 0; i < this->size; i++) { if(curr->getData()->getCustNumber() == customerNumber) { if(i == this->size-1) { prev->setNext(NULL); } else { prev->setNext(curr->getNext()); } delete curr->getData(); delete curr; this->size = this->size - 1; return true; }//end if prev = curr; curr = curr->getNext(); }//end loop return false; }
/** * Selecciona entre todos los individuos, * aletoriamente un invididuo, asigna probabilidades de exito * a los individuos con el fitness mas alto de la poblacion * Es un auxiliar */ Entity* Population::randomSelectTheFittest(){ //obtener un numero aleatorio, desde 0 hasta la suma de todos los fitnes multiplicado por la cantidad de genes int randomObtained= _Random->getRandomNumber(_Fitness->getSumOfAll()*Constants::CANTIDAD_DE_GENES); // cout<<"maximo :"<<_Fitness->getSumOfAll()*Constants::CANTIDAD_DE_GENES<<" . Random : "<<randomObtained<<endl; int cantidadElementos = this->_individuos->getLength(); Node<Entity*>* tmpNode = this->_individuos->getHead(); for(int i = 0; i<cantidadElementos; i++){ // cout<<"es la suma de todos : "<<_Fitness->getSumOfAll()<<endl; // cout<<"fitnes de :"<<i<<" es de: "<<_Fitness->caculateFitness(tmpNode->getData())<<endl; // cout<<"fitnes de :"<<i<<" es de: "<<_Fitness->caculateFitness(tmpNode->getNext()->getData())<<endl; // cout<<"fitnes de :"<<i<<" es de: "<<_Fitness->caculateFitness(tmpNode->getNext()->getNext()->getData())<<endl; //cout<<"random obtained: "<<randomObtained<<endl; // cout<<"multiplicado : "<<_Fitness->caculateFitness(tmpNode->getData()) *(_Fitness->getSumOfAll())<<endl; // cout<<"multiplicado : "<<_Fitness->caculateFitness(tmpNode->getNext()->getData()) *(_Fitness->getSumOfAll())<<endl; if( (_Fitness->caculateFitness(tmpNode->getData()) *_Fitness->getSumOfAll()) > randomObtained ){ //cout<<"seleccione al random mas apto, con ataque = "<<tmpNode->getData()->getGenome()->getAttack()<<endl; break; } randomObtained = randomObtained - (_Fitness->caculateFitness(tmpNode->getData())*_Fitness->getSumOfAll()); tmpNode = tmpNode->getNext(); } return tmpNode->getData(); }
/* insert one node before iterator */ void List::insert(Iterator iter,Data s) { Node *newNode = new Node(s); // Insert before()==================== /*newNode ->setPrev(iter.position->getPrev()); newNode ->setNext(*iter.position); cout<< newNode->getData().get()<<"new node data"<<endl; iter.position->setPrev(*newNode); iter.position->getPrev().setNext(*newNode); */ //insert After()======================= newNode ->setPrev(*iter.position); newNode ->setNext(iter.position->getNext()); cout<< newNode->getData().get()<<"new node data"<<endl; iter.position->setNext(*newNode); iter.position->getNext().setPrev(*newNode); //insert After()====== decouple=============== ??????== // iter.position->add(*newNode); cout<< newNode->getData().get()<<"new node data"<<endl; //tmp.position->getPrev().setNext(*newNode); //cout<< tmp.get()<<"==try with tmp =should be== 2==="<<endl; /*iter.previous(); cout<< iter.get()<<"===in iter pos 8sh Insert"<<endl; iter.previous(); cout<< iter.get()<<"===in Insert"<<endl; iter.previous(); cout<< iter.get()<<"===in Insert"<<endl; iter.previous(); cout<< iter.get()<<"===in Insert"<<endl; iter.previous(); cout<< iter.get()<<"===in Insert"<<endl; iter.previous(); cout<< iter.get()<<"===in Insert"<<endl; */ //=================================uncomment about got error 8new node data //1===in iter pos 8sh Insert //-1075377468===in Insert //1617430532===in Insert iter.goHead(); cout<< iter.get()<<"===in iter pos next be 8shInsert"<<endl; iter.next(); cout<< iter.get()<<"===in Insert"<<endl; iter.next(); cout<< iter.get()<<"===in Insert"<<endl; iter.next(); cout<< iter.get()<<"===in Insert"<<endl; iter.next(); cout<< iter.get()<<"===in Insert"<<endl; iter.next(); cout<< iter.get()<<"===in Insert"<<endl; }
Node<T>* LinkedList<T>:: addToList( T &item ){ // cout << "HERE " ; Node<T>* newNode = new Node<T> ( item , NULL ); Node<T>* nPtr = head , *pPtr = head ; if(head == NULL ){ head = newNode ; head->setNext(NULL); return newNode ; } // cout << ":O \n" ; T c = nPtr->getData() ; bool b = 0 ; while( nPtr != NULL && c < item ){ b = 1 ; pPtr = nPtr ; nPtr = nPtr->getNext() ; if( nPtr == NULL ) break ; c = nPtr->getData() ; } if( c == item ) return nPtr ; if( pPtr == head && nPtr != head ){ newNode->setNext( nPtr ) ; pPtr->setNext( newNode ) ; } else if( /*( pPtr == head && nPtr == head && nPtr->getNext() != NULL ) ||*/ b == 0 ){ newNode->setNext( nPtr ) ; head = newNode ; //pPtr->setNext( newNode ) ; } else if( pPtr->getNext() != NULL ){ newNode->setNext( pPtr->getNext() ) ; pPtr->setNext( newNode ) ; } else{ pPtr->setNext( newNode ) ; newNode->setNext( NULL ) ; } return newNode ; }
Token* TreeIterator::getPreorder() { // lastFlag is a flag that is used so getCurrentLevel returns the // correct level. This is necessary because if we just read the last // child of the node iter is pointing to, iter gets moved up a level // and curLevel gets decremented. However, the actual level we were on // doesn't change until NEXT time through. See how this is used in the // getCurrentLevel() method in the .h file. lastFlag = false; // If there are no nodes in the tree or the head node is a terminal, // something is wrong. Just return null. Also will fail when we are done // with the traversal. if(iter != NULL && iter->getData() == NULL) { Node* child = iter->getChild(indices.back()); // If getData() doesn't return null, we have a leaf node with actual // data to return. if(child->getData() != NULL) { Token* ret = child->getData(); // Now we have use a stack to keep track of all the indices in the // children arrays of all the nodes we are at. If we had a normal // traversal function that did something to every node, we would not // need such a stack. However, since we are returning nodes one at a // time, we need to keep track of "where we are" on each node's children. // Increment top of stack so we will return next child next time. int back = indices.back(); indices.pop_back(); indices.push_back(back + 1); // If we are returning the last child of the current node, we are done with // this branch and need to move the iterator up a level to keep going with // the traversal. if(indices.back() >= iter->getNumChildren()) { indices.pop_back(); int back = indices.back(); indices.pop_back(); indices.push_back(back + 1); iter = iter->getParent(); curLevel--; // special case where we don't want curLevel to "actually" go up till next time lastFlag = true; } return ret; } // We are on on interior node, so move down a level and try again to // find a leaf. else { indices.push_back(0); iter = child; curLevel++; return getPreorder(); } } return NULL; }
/** * * @param rightSide The CompareList to be assigned. * @return A reference to the CompareList to be assigned */ CompareList& CompareList::operator = (const CompareList& rightSide) { if (this != &rightSide) { removeAll(); Node* temp = rightSide.root; while (temp != NULL) { this->insert(temp->getData()->getChar(), temp->getData()->getSpace()); } } return *this; }
void Node::print() { Node *p = this; while (p->hasNext()){ cout<<p->getData()<<" -> "; p = p->getNext(); } cout<<p->getData()<<endl; }
void Graph::topologicalsort_util(int start,bool visited[],Stack<int> *s) { Node<int> *curr = array[start].gethead(); visited[start] = true; while (curr != NULL) { if (!visited[curr->getData()]) topologicalsort_util(curr->getData(), visited, s); } s->push(start); }
/*********************************************************************** * INPUT: the list makes up a number, first node has the low order digits, * the second node has next lowest etc. * OUTPUT: print the number to screen high order digits first. the lastNode * does not have leading zeros output to the screen, all others do. ***********************************************************************/ void ListNum::outputNum() { Node* tempPtr = lastNode; while (tempPtr != NULL) { if (tempPtr->getNext() == NULL) cout << setfill(' ') << setw(1) << tempPtr->getData(); else cout << setfill('0') << setw(9) << tempPtr->getData(); tempPtr = tempPtr->getPrevious(); } }
/** * * @param output A reference to the output stream. * @param rightSide The CompareList to print. * @return An output stream. */ std::ostream& operator << (std::ostream& output, const CompareList& rightSide) { Node* temp = rightSide.root; if (temp != NULL) { output << *(temp->getData()); temp = temp->getNext(); while (temp != NULL) { output << ", " << *(temp->getData()); temp = temp->getNext(); } } return output; }
/** * @param n The number of Nodes to print.. * @output The output stream to print to. */ void CompareList::print(int n, std::ostream* output) { Node* temp = root; int count = 0; if (temp != NULL && n > 0) { *output << *(temp->getData()); temp = temp->getNext(); count++; while (temp != NULL && count < n) { *output << ", " << *(temp->getData()); temp = temp->getNext(); count++; } } *output << std::endl; }
int main(){ //First node ptr Node* head; //Start list at 5 head = new Node(5); cout << "Data in node is: " << head->getData() <<endl; //Data of list int arr[5] = {6,7,8,9,10}; //Build list int i = 0; while(arr[i]){ append(head, arr[i]); i++; } //Current list cout << "Before inserting 4"<<endl; cout << "First in list: " << head->getData() <<" 2n: "<< head->getNext()->getData() << " 3rd: " << head->getNext()->getNext()->getData() <<endl; //Insert new data head = insert(head, 4); //Show results cout << "First in list: " << head->getData() <<" 2n: "<< head->getNext()->getData() << " 3rd: " << head->getNext()->getNext()->getData() <<endl; //Delete 6 head = deleteNode(head, 6); //Show results cout << "First in list: " << head->getData() <<" 2n: "<< head->getNext()->getData() << " 3rd: " << head->getNext()->getNext()->getData() <<endl; //Delete the head head = deleteNode(head, 4); cout << "First in list: " << head->getData() <<endl; cout << " 2nd: "<< head->getNext()->getData() <<endl; cout << " 3rd: " << head->getNext()->getNext()->getData() <<endl; return 0; }
// Determine if palindrom using reverse and no memory static bool isPalindromeReverse(Node<T> *head) { Node<T> *pt1 = head; Node<T> *pt2 = head; int count = 0; while (pt2 != nullptr) { if (count % 2 == 0) { pt1 = pt1->getNext(); } pt2 = pt2->getNext(); ++count; } Node<T> *reverse = reverseList(pt1); pt1 = head; while (reverse != nullptr) { if (reverse->getData() != pt1->getData()) { return false; } reverse = reverse->getNext(); pt1 = pt1->getNext(); } return true; }
/** * @brief helper methodfor remove() * @details recursively search for the parent of the removal target.\n * Once found, remove it accordingly in 1 of 4 scenarios. * * @param node the node potential to be the removal target's parent * @param rmToken the removal target string * * @return removal success status */ bool TBST::remove(Node* node, string rmToken) { string nodeToken = node->getData()->getToken(); bool targetIsOnLeft = (rmToken < nodeToken); Node* rmTarget; // looking for the removal node if (targetIsOnLeft) { if (node->hasLeftChild()) { rmTarget = node->getLeft(); } else { return false; } } else { if (node->hasRightChild()) { rmTarget = node->getRight(); } else { return false; } } // if found, then remove with 1 of 4 cases if (rmToken == rmTarget->getData()->getToken()) { if (rmTarget->isLeaf()) { return rmLeaf(node, targetIsOnLeft); } else if (rmTarget->hasLeftChild() && !rmTarget->hasRightChild()) { return rmNodeWithLeft(node, targetIsOnLeft); } else if (rmTarget->hasRightChild() && !rmTarget->hasLeftChild()) { return rmNodeWithRight(node, targetIsOnLeft); } else { return rmNodeWithBoth(node, targetIsOnLeft); } // otherwise, recurse } else { return remove(rmTarget, rmToken); } }