1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
|
#include "linkedlist.h"
LinkedList::~LinkedList()
{
//dtor
}
ostream& operator<<(ostream& o, LinkedList ll)
{
Node *ptr = ll.myHead;
o << "[ ";
while (ptr)
{
o << "(" << ptr->getData() << ") ";
ptr = ptr->getNext();
}
o << "]";
return o;
}
void LinkedList::pushBack(string data)
{
if (isEmpty())
{
myHead = myTail = new Node(data, 0);
}
else
{
Node *ptr = new Node(data, 0);
myTail->setNext(ptr);
myTail = ptr;
}
}
void LinkedList::pushFront(string data)
{
if (isEmpty())
{
myHead = myTail = new Node(data, 0);
}
else
{
myHead = new Node(data, myHead);
}
}
bool LinkedList::isEmpty()
{
return (!myHead);
}
string LinkedList::popFront()
{
if (isEmpty())
{
cerr << "ERROR ... POPPING FROM AN EMPTY LIST!" << endl;
exit(1);
}
string temp = myHead->getData();
myHead = myHead->getNext();
return temp;
}
void LinkedList::printRecursive()
{
cout << "[" << myHead << "]" << endl;
}
void LinkedList::mergeSort()
{
if (myHead != myTail) // more than one element
{
LinkedList l1,l2;
split(l1,l2);
l1.mergeSort();
l2.mergeSort();
merge(l1,l2);
}
}
// deal the current list into two new lists
void LinkedList::split(LinkedList &l1, LinkedList &l2)
{
while (!isEmpty())
{
l1.pushBack(popFront());
if (!isEmpty())
{
l2.pushBack(popFront());
}
}
}
// take the lowest element from one of the two lists
// and add it to the back of the current list
void LinkedList::merge(LinkedList &l1, LinkedList &l2)
{
while (!l1.isEmpty() && !l2.isEmpty())
{
if (l1.getFront() < l2.getFront())
{
pushBack(l1.popFront());
}
else
{
pushBack(l2.popFront());
}
}
// one list is empty at this point
while (!l1.isEmpty())
{
pushBack(l1.popFront());
}
while (!l2.isEmpty())
{
pushBack(l2.popFront());
}
}
void LinkedList::createList()
{
ifstream fin;
ofstream fout;
string inputBuffer, inputFile, outputFile;
cout << "Please enter the name of the file you wish"
<< " to merge sort: ";
cin >> inputFile;
cout << "Please enter the name of the file you wish"
<< " to output data into: ";
cin >> outputFile;
fin.open(inputFile.c_str());
fout.open(outputFile.c_str());
if (!fin)
{
cout << "File cannot be found" << endl;
exit(1);
}
fin.ignore(1000, '\n');
do{
getline(fin, inputBuffer);
fout << inputBuffer << endl;
}while (!fin.eof());
for (Node *temp = myHead; temp; temp = temp->getNext())
{
string tempString;
tempString = temp->getData();
fout << tempString << endl;
}
fout.close();
fin.close();
}
|