I'm learning c++ and am attempting to maintain a linked list in alphabetical order. If I were to input a list of names say "Mary, bob, sally, larry, david, roger" I would expect them to print out (after traversing the list) "bob, david, larry, mary, roger, sally". Any help would be greatly appreciated. Thank you!
Note: The code is not printing the names in alphabetical order when I attempt to execute it. Apologies, thought I wrote that, but apparently I did not. It compiles fine, but the results produced are not what is expected.
EDIT: I noticed something interesting. I'm receiving an error when I attempt to build the file c:/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot open output file Program18ContactList.exe: Permission denied collect2.exe:error: 1d returned 1 exit status
It runs, but when i attempt to rebuild any changes I get that message. I get the idea of what it means, but am unsure how to fix it. I haven't deleted any source files. I am using the newest version of Eclipse Mars.2
Main
//Contact list playing with classes
//Contact lists
#include "ContactList.H"
using namespace std;
int main()
{
ContactList* cl1 = new ContactList();
string name;
while(true)
{
cout << "Enter the name of the contact or q to quit." << endl;
cin >> name;
if(name == "q")
{
break;
}
cl1->insert(name);
}
cl1->printList();
return(0);
}
Class
//contact list class
#include "ContactList.H"
using namespace std;
ContactList::ContactList():head(0), size(0)
{}
void ContactList::addToHead(const string& name)
{
Contact* newOne = new Contact(name);
if(head == 0)
{
head = newOne;
}
else
{
newOne->next = head;
head = newOne;
}
size++;
}
void ContactList::printList()
{
Contact* tp = head;
while(tp != 0)
{
cout << *tp << endl;
tp = tp->next;
}
}
void ContactList::insert(const string& name)
{
Contact* newNode = new Contact(name);
// case 1 - empty list
if(head == 0)
{
//assigns new node to the empty list head node
head = newNode;
}
else
{
//current pointer initialized to the head so as to start traversal
// trail pointer initialized to zero, but will iterate one step behind
// current to keep former data location on the stack organized
Contact* curr = head;
Contact* trail = 0;
// Traverse list to find insert location
while(curr != 0)
{
if(curr->name >= newNode->name)
{
break;
}
else
{
trail = curr;
curr = curr->next;
}
}
// case 2 - insert at head (not empty)
if(curr == head)
{
newNode->next = head;
head = newNode;
}
else
{
// case 3 - insert after the head (not empty)
newNode->next = curr;
trail->next = newNode;
}
}
size++;
}