//----------------------------------- // List Node //----------------------------------- template class Node{ public: Node(); T getKey() const; void setKey(T k); Node * getNext() const; void setNext(Node * n); private: T key; Node * Next; }; template Node::Node(){ Next = NULL; } template T Node::getKey() const{ return key; } template void Node::setKey(T k){ key = k; } template Node * Node::getNext() const{ return Next; } template void Node::setNext(Node * n){ Next = n; } //----------------------------------- // List //----------------------------------- template class List{ public: List(); int findKey(T k) const; int addKey(T k); int removeKey(T k); void printList() const; private: Node *root; }; template List::List(){ root = NULL; } // return 1 if k is found else return 0 template int List::findKey(T k) const{ Node * ptr1; ptr1 = root; while (ptr1 != NULL){ if (ptr1->getKey() == k) return 1; else ptr1 = ptr1->getNext(); } return 0; } template int List::addKey(T k){ // check if it exists if (findKey(k)){ return 0; } // create new node Node *newNode; newNode = new Node; newNode->setKey(k); // find the pos Node *ptr1, *ptr2; ptr1 = ptr2 = root; while (ptr1 != NULL && ptr1->getKey() < k){ ptr2 = ptr1; ptr1 = ptr1->getNext(); } // insert it if (ptr1 == root){ newNode->setNext(root); root = newNode; return 1; } newNode->setNext(ptr1); ptr2->setNext(newNode); return 1; }; template int List::removeKey(T k){ // check if it exists if (findKey(k) != 1){ return 0; } // find the pos Node *ptr1, *ptr2, *rNode; ptr1 = ptr2 = root; while (ptr1 != NULL && ptr1->getKey() != k){ ptr2 = ptr1; ptr1 = ptr1->getNext(); } // remove it if (ptr1 == root){ rNode = root; root = root->getNext(); delete rNode; return 1; } rNode = ptr1; ptr2->setNext(ptr1->getNext()); delete rNode; return 1; }; template void List::printList() const{ Node * ptr1; ptr1 = root; while (ptr1 != NULL){ cout << ptr1->getKey() << "=> "; ptr1 = ptr1->getNext(); } cout << "NULL" << endl; };