#include "stdstuff.h" #include "List.h" // the destructor destroys the list one node at a time, starting from the head List::~List () { Node *t; while (head != NULL) { t = head; head = head -> next; delete t; } } // prints the list to cout one node at a time, starting with the head void List::outputList () const { Node *c = head; int i = 0; cout << "The list contains:" << endl; while (c != NULL) { cout << " " << c -> data; if (++i == 10) { cout << endl; i = 0; } c = c -> next; } if (i != 0) cout << endl; } // inserts a node into the list at the head of the list void List::insert (int data) { head = new Node (data, head); } // Method "sumEvenValues" returns the sum of the nodes in the list containing even values. // Note that "containing" refers to the *contents* of the node, not its position in the list. // If the list has no even values, it returns 0. int List::sumEvenValues() const { int sum = 0; for (Node* c = head; c!=NULL; c=c->next) { // check every node if (c->data%2==0) // if it's even, add to the sum sum += c->data; } return sum; } // Method "deleteEveryThirdNode" deletes the 3rd, 6th, 9th, etc. node of the list. // Note that the list starts with the first (not "zeroth") node. // If the list has fewer than three nodes, this method has no effect. void List::deleteEveryThirdNode() { Node *c = head, *p, *temp; while (c!=NULL && c->next!=NULL && c->next->next!=NULL) { // while there are at least 3 nodes left to check p = c->next; c = c->next->next; // c now points to the node to delete, and p to the previous node (and p is never NULL) p->next = c->next; // make previous node point to next node in preparation for deletion temp = c; c = c->next; // move on to next node delete temp; // and delete the one that was in the 3rd, 6th, etc. position in the list } }