#include#include using namespace std; struct Node { char _data; Node *_next; Node() { this->_next = 0; this->_data = 0; } Node(char ch) { this->_data = ch; this->_next = 0; } ~Node() { } }; class LinkedList { private: Node *_header; int listCount; public: LinkedList(); ~LinkedList(); Node *getHeader(); void setHeader(Node *_passed); string out(void); void add(char ch); bool find(char ch); bool findRecurse(char ch, Node *current, bool &found); bool del(char ch); bool delRecurse(char ch, Node *current, bool &found); friend std::ostream& operator<<(std::ostream& out, LinkedList& list); };
#include "linkedlist.h" #include#include using namespace std; ostream& operator<<(ostream &os, LinkedList& list){ os << list.out(); return os; } LinkedList::LinkedList() { this->listCount = 0; this->_header = new Node; this->_header->_next = NULL; } LinkedList::~LinkedList() { Node *current = this->getHeader(); Node *temp; while(current != NULL) { temp = current->_next; delete current; current = temp; } } string LinkedList::out(void) { Node *current = this->getHeader(); string buff; buff += "\n"; if(listCount == 1) { buff = current->_data; } else { while (current != NULL) { buff += current->_data; current = current->_next; } } buff += "\n"; return buff; } Node* LinkedList::getHeader(void) { return this->_header; } void LinkedList::setHeader(Node *_passed) { this->_header = _passed; } void LinkedList::add(char ch) { Node *current = this->getHeader(); Node *temp = new Node(ch); while(current->_next != NULL) { current = current->_next; } current->_next = temp; cout << endl << ch << " added."; } bool LinkedList::find(char ch) { bool found = false; findRecurse(ch, this->getHeader(), found); return found; } bool LinkedList::findRecurse(char ch, Node *current, bool &found) { if(current->_data == ch) { cout << endl << ch << " found!" << endl; found = true; return found; } else if(current->_data != ch && current->_next != NULL && found == false) { findRecurse(ch, current->_next, found); } if(!found) { return found; } } bool LinkedList::del(char ch) { bool found = false; delRecurse(ch, this->getHeader(), found); return found; } bool LinkedList::delRecurse(char ch, Node *current, bool &found) { Node *temp; // temp pointer for deletion if(current->_data == ch && current == this->getHeader()) // if headcased { this->listCount--; // decrement list cout << endl << "deleting " << ch; this->setHeader(current->_next); // set header to next delete current; // delete found = true; // set as found } else if(current->_next->_data == ch && found == false) { this->listCount--; // decrement list cout << endl << "deleting " << ch; temp = current->_next; // set temp to hold position current->_next = current->_next->_next; // break chain delete temp; // use temp to remove found = true; // set as found } else if(found != true && current->_next != 0) // able to recurse, not found { delRecurse(ch, current->_next, found); } return found; // return finding }