Hello thar,
I'm working on a problem that needs to input data into a list in sorted order. So far I'm getting some output, but it ignores some of my inserts, (ie "Hammy" in this case) and the output is not sorted.
I've looked at this for a while but I can't seem to find what I'm doing wrong, part of me believes its in one of my if statements, I'll denote it in the code.
Any help would be appriciated!
#include <iostream>
#include <string>
using namespace std;
struct Node
{
string value;
struct Node * next;
};
class List
{
public:
List()
{
cout << "Creating a new list..." << endl;
top = new Node;
top->value = "INVALID";
top->next = NULL;
end = NULL;
count = 0;
}
int getCount()
{
return count;
}
void deleteIt(string data)
{
Node *x = top;
Node *prev = NULL;
while (x != NULL){
if (x->value != data){
prev = x;
x = x->next;
}
else if (x->value == data){
prev->next = x->next;
delete x;
count --;
return;
}
}
}
void SortInsert(string data)
{
Node *tmp = new Node;
Node *prev = NULL;
Node *x = top->next;
tmp->next = NULL;
x = top;
if (x == NULL)
{
top = tmp;
}
else
{
while (x != NULL)
{
if (x->next == NULL)
{
x->next = tmp;
break;
}
else if (data < x->value) // THIS STATEMENT
{
tmp->value = data;
tmp->next = x->next;
x->next = tmp;
count ++;
break;
}
x = x->next;
}
}
}
void print()
{
Node *x = top;
bool header = true;
cout << "Here is the list: " << endl;
while (x != NULL)
{
if (!header)
cout << x->value << endl;
else
header = false;
x = x->next;
}
cout << "End of list" << endl;
}
bool has(string what)
{
Node *x = top;
bool header = true;
while (x != NULL)
{
if (!header)
{
if (x->value == what)
return true;
}
else
header = false;
x = x->next;
}
return false;
}
private:
Node *top;
Node *end;
int count;
};
int main()
{
List myList;
/*myList.insert("Adam");
myList.insert("Betty");
myList.insert("Betty");
myList.insert("Charlie");
myList.deleteIt("Charlie");*/
myList.SortInsert("Hammy");
myList.SortInsert("Brian");
myList.SortInsert("Albert");
myList.SortInsert("Freefall");
cout << "There are " << myList.getCount() <<
" item(s) in the list" << endl;
myList.print();
if (myList.has("Adam"))
cout << "The list does contain Adam" << endl;
if (myList.has("Betty"))
cout << "The list does contain Betty" << endl;
if (myList.has("Charlie"))
cout << "The list does contain Charlie" << endl;
if (myList.has("Steve"))
cout << "The list does contain Steve" << endl;
}