Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify Linked List to be an ordered linked list sorted in alphabetical order by

ID: 3658590 • Letter: M

Question

Modify Linked List to be an ordered linked list sorted in alphabetical order by the item name (char array). // The driver for Shopping example (linked List). #include #include #include "shopping.h" using namespace std; int main() { Shopping *head = NULL; void buildList(ifstream &, Shopping *&); ifstream myfile("shoplist.txt"); if (myfile.fail()) { cerr << "Cannot open input file "; return 1; } buildList(myfile, head); if (head) head->sort();///Add this.... if (head) head->show(); if (head) head->clean(); myfile.close(); return 0; } // main void buildList(ifstream &infile, Shopping *&h) { char s[21]; int k; Shopping *temp; if (infile.eof()) return; // stop recursive call infile >> k >> s; temp = new Shopping(k, s); temp->addItem(h); buildList(infile, h); // recursive call } // buildList // shopping.h declares the Shopping class #ifndef SHOPPING #define SHOPPING class Shopping { protected: static Shopping *tail; // class attribute int QTY; char item[21]; Shopping *next; public: Shopping(int, char *); // constructor void addItem(Shopping *&); void show(); void clean(); void sort(); ///add this .... }; // Shopping #endif //shopping.cpp Implementation file for the Shopping class #include "shopping.h" #include #include using namespace std; Shopping * Shopping::tail = NULL; Shopping::Shopping(int v, char *s) { QTY = v; strcpy(item, s); next = NULL; } // constructor void Shopping::addItem(Shopping *& h) { if (h == NULL) // the list is empty { h = this; tail = this; } else { tail->next = this; tail = this; } } // addItem void Shopping::show() { cout << QTY << " " << item << endl; if (next) next->show(); // recursive call to the neighbor } // show void Shopping::clean() { Shopping *t = next; delete this; if (t) t->clean(); } // clean Please help I think I need to use an sorted array but not really sure. void Shopping::sort() int swapped = 1; while(swapped) { ItemTypePtr p = head; swapped = 0; while(p->nextItem!=NULL) { if (strcmp(p->itemName, p->nextItem->itemName) > 0) { //swap temp=item[p]; found=true swapped = 1; } p = p->nextItem; } } }

Explanation / Answer

void Shopping::sort(Shopping *head) { bool swapped = false; if (head!=NULL && head->next!=NULL) { Shopping *curr=head; while(!curr->next) { Shopping * curr1 = curr->next; while(curr->next!=NULL) { if (strcmp(curr->item, curr1->item) > 0) { char temp[21]; for (int i=0;iitem[i]; for (int i=0;iitem[i]=curr1->item[i]; for (int i=0;iitem[i]=temp[i];//SWAP DATA curr1=curr1->next; } curr = curr->next; } } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote