/* * This is a solution to the LinkedList.cpp program you were asked to write for this week. Note * that is doesn't contain as many comments as usual because many were already provided in the * skeleton file, so only some implementation issues will be pointed out here. * */ #include using namespace std; class LinkedList { private: class Node { public: char data; Node *next; }; Node *first; public: LinkedList(); void insert(char dat); void print(); ~LinkedList(); }; //Main program tests the class by inserting a few values and then printing out the list. int main() { LinkedList list; list.insert('a'); list.insert('b'); list.insert('b'); list.print(); return 0; } LinkedList::LinkedList() { first = NULL; } //Insert method creates a new node for every data value, even if it is already in the list. The //insertion algorithm should be familiar from data strucures. void LinkedList::insert(char dat) { Node *newNode = new Node; newNode->data = dat; newNode->next = NULL; if(first == NULL) { first = newNode; } else{ Node *current; current = first; while(current->next != NULL) { current = current->next; } current->next = newNode; } } //Print out the list by looping through it, unless the list is empty in which case we tell the user //that. Again, the algorithm should be familiar from data structures. void LinkedList::print(){ Node *current; current = first; if(current == NULL) { cout << "There are no nodes in the list."; } else { while(current != NULL) { cout << current->data << endl; current = current->next; } } } //The class destructor. While it looks simple it is actually surprisingly tricky to write. The key //is moving forward through the list and updating first. LinkedList::~LinkedList() { Node *current; while(first != NULL) { //Set curent equal to the first pointer. current = first; //Reset first to point to the next node in the list. first = first->next; //Delete the first node in the list so that we don't leak memory, and repeat. delete current; } }