//Syed Rais Ahmad //Assignment # 5 Quest 6 //Circular List.Del every 2nd,free all nodes, return sum of ints #include //A node in a list class llistItem { public: int item; llistItem * nxtItem; }; //circular List class cList { private: llistItem *rear; public: cList(); ~cList() {delete rear;}; void DelEvery2nd(void); bool Insert(int); int Remove(); bool isEmpty(); void printAll(); void freeAll(); int total(); }; //create rear and put NULL values in it. cList::cList() { rear = new llistItem; rear->nxtItem=NULL;//Empty cList } //return the total of all integers in list int cList::total() { if (!isEmpty()) { llistItem * ptr=rear->nxtItem; int total=ptr->item; while((ptr=ptr->nxtItem)!=rear->nxtItem) total+=ptr->item; return total; } return 0; } //Return an item. -1 if stack is empty int cList::Remove() { if (!isEmpty()) { llistItem * front,* temp; int i=0; //front gets the address of next node from rear front=rear->nxtItem->nxtItem; //if only one node is remaining then front = rear; if (front==rear->nxtItem) { i=front->item; delete front; rear->nxtItem=NULL; //empty the cList return i; } //temp gets the about-to-be front node's address. temp=front->nxtItem; i=front->item; //rear node now points to a new front node. rear->nxtItem->nxtItem=temp; delete front; return i; } return -1; } //Delete Every Second Entry from list void cList::DelEvery2nd() { llistItem * ptr=rear->nxtItem,*temp; while(1) { temp=ptr->nxtItem->nxtItem; if (ptr->nxtItem==rear->nxtItem) break; else delete ptr->nxtItem; ptr->nxtItem=temp; if ((ptr=ptr->nxtItem)==rear->nxtItem) break; } } //free all nodes in cList void cList::freeAll() { while(!isEmpty()) Remove(); } //print all values stored in list void cList::printAll() { if (!isEmpty()) { llistItem * ptr; ptr=rear->nxtItem; while((ptr=ptr->nxtItem)!=rear->nxtItem) cout << '\n' << ptr->item; cout << '\n' << ptr->item; } } //Insert an int to a cList bool cList::Insert(int insInt) { llistItem * ptr,*temp; //insert will always need new node with new integer value in it. ptr=new llistItem; ptr->item=insInt; if (isEmpty()) { //node points to itself ptr->nxtItem=ptr; rear->nxtItem=ptr; } else { //temp holds value for node next to rear node. temp=rear->nxtItem->nxtItem; //rear is now the new node, just inserted. rear->nxtItem->nxtItem=ptr; ptr->nxtItem=temp; //rear points to a newly inserted node. rear->nxtItem=ptr; } return true; } //is cList Empty bool cList::isEmpty() { return (rear->nxtItem==NULL)? true : false; } //------- Program's main flow starts --------------------------- main() { cList q;int i=0; for(;i<10;i++) q.Insert(i); //print the original list cout << "\nList is:"; q.printAll(); //del every other cout << "\nDeleting Every other Element:\n"; q.DelEvery2nd(); cout << "\nList becomes:" ; q.printAll(); //total the value of all nodes cout << "\nTotal is:\n"; cout << q.total() << '\n'; //Free all nodes cout << "\bFreeing All nodes...\nList becomes:\n"; q.freeAll(); q.printAll(); return 0; }