//CIS 610: Lists //Syed Rais Ahmad //Assignment # 5 Question 4. #include class llistItem { public: int item; llistItem * nxtItem; }; class lList { private: llistItem * head; public: lList(); ~lList() {delete head;}; void add(int addInt); void getall(); void swap(int,int); }; //Init lList::lList() { head = new llistItem; head->nxtItem=NULL; head->item=NULL; } //add to the tail of link list void lList::add(int addInt) { llistItem * ptr=head; //a temporary listitem pointer holds head address of link list. while(ptr->nxtItem) ptr=ptr->nxtItem; //reach the item whose nextitem points to NULL address ptr->nxtItem=new llistItem; //add a new list item ptr=ptr->nxtItem; // temporary pointer holds new item's address ptr->item=addInt; // add a value to new item ptr->nxtItem=NULL; //make next item of new item point to NULL } //print all items in the link list. void lList::getall() { llistItem * ptr=head; //ptr gets the head value while (ptr=(ptr->nxtItem)) //while ptr points to not NULL value cout << ptr->item << "\n"; } void lList::swap(int m,int n) { int i=0,first,sec;llistItem * ptr, * temp; ptr=head; if (m!=n) { //while traversing list, first will be encountered first first=(m>n)? n: m; sec=(first==m)? n : m; //traverse the list to first item. Store its address and value while(i++nxtItem) ptr=ptr->nxtItem; temp=ptr; first=ptr->item; i--; //traverse to second item. Swap the values now. while(i++nxtItem) ptr=ptr->nxtItem; sec=ptr->item; ptr->item=first; temp->item=sec; } } //------- Program's main flow starts --------------------------- main() { lList l; l.add(9); l.add(4); l.add(5); l.add(6); l.add(74); l.add(84); cout << "\nItems in List are:\n"; l.getall(); cout << "\nSwap items 3rd and 5th:\n"; l.swap(3,5); cout << "\nItems in List are:\n"; l.getall(); return 0; }