#include "listNode.h" #include "listIterator.h" #include "list.h" using namespace std; // Constructor for Class List List::List() {last = first = 0; cout << "allocated List " << this << endl; } // Copy Constructor for Class List List::List(const List & fr) {cout << "Copy Constructructor from List " << &fr << " to List " << this << endl; ListNode *ptr, *tptr; this->first = this->last = 0; ptr = fr.first; while(ptr) { tptr = new ListNode(ptr->GetData()); if (this->first == 0) {this->first=this->last=tptr;} else {this->last->SetNext(tptr); this->last = tptr; } ptr=ptr->GetNext(); } return; } List::~List() { cout << "deallocated List " << this << endl; this->Erase(); last = first = 0; } void List::operator=(const List & fr){ cout << "Assignment Operator from List " << &fr << " to List " << this << endl; if (this == &fr) return; this->Erase(); // Memory leak eliminated. this->Concatenate(fr); // Will not work for s = t = m; return; } List List::operator+(const List & fr){ cout << "Addition Operator for List " << &fr << " to List " << this << endl; List t; t.Concatenate(*this); t.Concatenate(fr); return t; } ostream & operator<<(ostream & os, const List & fr) { ListIterator li (fr); while( ! li.Done() ) { os << li.CurrentData() << " Listode " << li.CurrentPtr() << endl; li.Advance(); } return os; } istream & operator>>(istream & is, List & fr) { int contents; cout << "Input a List. one element per line and ending with a line with just a zero" << endl; is >> contents; while (contents) {fr.InsertSorted(contents); is >> contents; } return is; } void List::InsertAfterNode(ListNode *p, int x) // Insert a ListNode after // certain ListNode in a List { ListNode *t = new ListNode(x); // create and initialize new node // insert after p t->SetNext( p->GetNext() ); p->SetNext( t ); if (last == p) last=t; } void List::InsertFront(int x) // Insert a ListNode at the // beginning of a List { ListNode *t = new ListNode(x); // create and initialize new node t->SetNext( first ); if (last == 0) last = t; first = t; } void List::InsertAtEnd(int x) // Insert a ListNode at the // end of a List { ListNode *t = new ListNode(x); // create and initialize new node if (last == 0) first = t; else last->SetNext( t ); last = t; } ListNode* List::GetFirst() const { return first;} void List::InsertSorted(int x) { // Insert a ListNode with data value x ListNode *p = first; if (p == 0) {InsertFront(x); return;} if (x == p->GetData()) return; if (x < p->GetData()) {InsertFront(x); return;} while (p->GetNext()) { if (p->GetNext()->GetData() == x) return; if (p->GetNext()->GetData() > x) {InsertAfterNode(p,x); return;} p = p->GetNext(); } InsertAfterNode(p,x); } void List::Concatenate(const List & fr) { ListIterator li (fr); while(! li.Done()) { this->InsertAtEnd(li.CurrentData()); li.Advance(); } return; } void List::Erase() { ListNode *ptr, *tempptr; ptr = first; while(ptr) { tempptr=ptr->GetNext(); delete(ptr); ptr=tempptr; } last = first = 0; }