/* ex1.cpp Single Linked List Class */ #include using namespace std; #include "clist.h" #include class CList { private: pNode m_head; pNode m_tail; int m_nextId; void killList (); int getNextID() {return m_nextId++;} public: CList (); ~CList(); void printList( pNode start); pNode AddElement(); pNode findKey(string searchKey); int Length(); }; CList::CList() { m_head=0; m_tail=0; m_nextId=0; } CList::~CList() { killList( ); } int CList::Length() { int Result =0; pNode Element = m_head; while (Element) { Result++; Element=Element->next; } return Result; } // Create a new node, initialize it add it to the end of the list pNode CList::AddElement( ) { pNode result=0; result=new Node; if (result) { result->data = new dataElement; result->next = 0; if (result->data) { result->data->id=getNextID(); result->data->key = ""; } if (!result->data) // element or its key failed so free up the node { delete result; result =0; } } // If built ok add to end of list if (result) { if (!m_tail) // we have an empty list! { m_tail = result; m_head = result; } else // point the current tail to the new node { m_tail->next= result; m_tail = result; // new node is now the tail } } return result; } void CList::printList( pNode start) { pElement element=0; while ( start ) { element = start->data; cout << "Id = " << element->id << "Key = element->key" << endl; start=start->next; } } pNode CList::findKey(string searchKey) { pNode start=m_head; pElement element=0; int found =0; while (start) { element = start->data; if (element->key.compare( searchKey )==0 ) // a match { return start; } else { start= start->next; } } return NULL; } void CList::killList () { pElement element=0; pNode node =0; while ( m_head ) { node = m_head; element = node->data; m_head = node->next; delete element; delete node; } } int main(int argc, char* argv[]) { pNode search=0; CList List; for (int i=0;i<100;++i) { pNode newNode = List.AddElement( ); if (!newNode) break; // Something failed so add no more pElement element=newNode->data; stringstream key(""); key << "KEYID:" << i; element->key= key.str(); } if (List.Length() >0) { search = List.findKey( "KEYID:78"); if (search) { pElement element=search->data; cout << "Element found at Id=" << element->id << endl; } else { cout << "Key not found" << endl; } } //List.printList( head ); return 0; }