// CS2310 Excise 15 // Chapter 16 // // Name ___________________________ SSN _______________________ // // p960 - 1 // To the SortedList2 class, add a value-returning // member function named Length that counts and returns // the number of nodes in a list. // // IMPLEMENTATION FILE DYNAMIC-LINKED SORTED LIST // ( slist2.cpp ) #include #include "slist2.h" using namespace std; bool SortedList2::IsEmpty ( ) const { return (head == NULL); } void SortedList2::Print ( ) const { NodePtr ptr = head; cout << "The elements in the list is:" << endl; while (ptr != NULL) { printf("%6d", ptr->item); ptr = ptr->link; } cout << endl; } void SortedList2::InsertTop ( /* in */ ItemType item ) { NodePtr location; location = new NodeType; location->item = item; location->link = head; head = location; } void SortedList2::DeleteTop ( /* out */ ItemType& item ) { NodePtr tempPtr; item = head->item; tempPtr = head; head = head->link; delete tempPtr; } SortedList2::SortedList2 ( ) { // Constructor // Post: head == NULL head = NULL; } SortedList2::~SortedList2 ( ) // Destructor // Post: All linked nodes deallocated { ItemType temp ; // keep deleting top node while ( !IsEmpty() ) DeleteTop ( temp ); } int SortedList2::Length(void) // POST: Return the number of elements in // the list. { NodePtr ptr = head; int count = 0; // Write the omitted code here: // Beginning from head, follow the link until // reach the end of the list. Count during the // tracing. return count; } int main() { SortedList2 slist; ItemType item; int i; for (i=0; i<5; i++) slist.InsertTop(i); slist.Print(); cout << "The number of elements in the list is: " << slist.Length() << endl << endl; for (i=0; i<3; i++) slist.InsertTop(i+5); slist.Print(); cout << "The number of elements in the list is: " << slist.Length() << endl << endl; for (i=0; i<4; i++) slist.DeleteTop(item); slist.Print(); cout << "The number of elements in the list is: " << slist.Length() << endl << endl; return 0; }