/* * File: list.cpp * Author: Robert I. Pitts * Last Modified: Fall 2000 * Topic: Templates * ----------------------------------------------------- * * This is the implementation for a linked list class. * */ #include #include "list.h" /* * Constructor * ------------------------- * List starts out empty (i.e., no nodes). */ List::List() { head = NULL; } /* Destructor * ----------------------- * This deallocates all memory associated with the list. */ List::~List() { // Since removeFromEnd() deallocates memory for the // node it removes, let it do the work. Inefficient if // removeFromEnd() is inefficient, but ok for now. while (head != NULL) removeFromEnd(); } /* * Function: insertAtBeginning * ----------------------- * Add an item to the beginning of the list. */ void List::insertAtBeginning(int item) { Node *newNode = new Node; newNode->item = item; // NOW LINK THE NODE INTO THE LIST. } /* * Function: removeFromEnd * ----------------------- * Remove the last node and return its item. Since we * are only using a pointer to the beginning ("head"), * we have to do the inefficient thing and search for * the last node, maintaining a "previous" pointer. */ int List::removeFromEnd() { if (head == NULL) { cerr << "can't remove from empty list" << endl; exit(1); // Terminate program. } else { Node *removeNode = head; Node *prev = NULL; while (removeNode->next != NULL) { prev = removeNode; removeNode = removeNode->next; } // FOUND THE NODE TO REMOVE, DEALLOCATE IT, FIX // ANY LINKS IN THE LIST, AND THEN RETURN THE ITEM. } } /* * Function: isempty * ----------------------- * Tells whether list is empty or not. */ bool List::isempty() const { return head == NULL; }