Add the operatiions save and restore to the pointer based implementation of the
ID: 3657903 • Letter: A
Question
Add the operatiions save and restore to the pointer based implementation of the ADT list. These operations use a file to save and restore the list items. Help is greatly appreciative.Explanation / Answer
///Storing is nothing but inserting and restoring is retieving in the following code #include "list.h" // header file #include #include List::List(): size(0), head(NULL) { } // end default constructor List::List(const List& aList) : size(aList.size) { if(aList.head == NULL) head = NULL; else{ head = new ListNode; head->item = aList.head->item; ListNode *newPtr = head; for(ListNode *origPtr = aList.head->next; origPtr != NULL; origPtr = origPtr->next){ newPtr->next = new ListNode; newPtr = newPtr->next; newPtr->item = origPtr->item; } newPtr->next = NULL; } } List::~List(){ while (!isEmpty()) remove(1); } bool List::isEmpty() const { return size == 0; } // end isEmpty int List::getLength() const { return size; } // end getLength List::ListNode *List::find(int index) const { if((index < 1) || (index > getLength())){ return NULL; } else{ ListNode *cur = head; for (int skipper = 1; skipper next; return cur; } } } void List::retrieve(int index, ListItemType& dataItem) const throw (ListIndexOutOfRangeException) { if ( (index getLength())){ throw ListIndexOutOfRangeException( "ListIndexOutOfRangeException:retrieve index out of range"); }else{ ListNode *cur = find(index); dataItem = cur->item; } } void List::insert(int index, const ListItemType& newItem) throw(ListIndexOutOfRangeException, ListException) { int newLength = getLength() + 1; if((index < 1) || (index > newLength)){ throw ListIndexOutOfRangeException( "ListIndexOutOfRangeException:retrieve index out of range"); }else{ try { ListNode *newPtr = new ListNode; size = newLength; newPtr->item = newItem; if(index == 1){ newPtr->next = head; head = newPtr; }else{ ListNode *prev = find(index - 1); newPtr->next = prev->next; prev->next = newPtr; } } catch (bad_alloc e) { throw ListException("ListException: insert cannot allocate enough memory."); } } } void List::remove(int index) throw (ListIndexOutOfRangeException) { ListNode *cur; if( (index getLength())){ throw ListIndexOutOfRangeException( "ListIndexOutOfRangeException: remove index out of range"); }else{ --size; if(index == 1){ cur = head; head = head->next; }else{ ListNode *prev = find(index-1); cur = prev->next; prev->next = cur->next; } cur->next = NULL; delete cur; cur = NULL; } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.