My task is a create doubly linked list and sort them according to their data, if new written node's data is equal to the one of the nodes' data in my doubly linked list, i should sort them in a alphabetical order but I am stuck in the function strcmp(temp->name, newnode->name)
,
For example, I am trying to check if these values entered in order
My sorted doubly linked list give the output as
Here is example of my code
struct node {
int data;
string name;
node* left;
node* right;
node(int i = 0, string s = "", node* l = nullptr, node* r = nullptr) : data(i), name(s), left(l), right(r) {}
};
struct node* head = NULL;
struct node* tail = NULL;
at the top of the program
void insert(int newdata, string name) // Used for insertion at the end of the linked list and make
{ // the connection for each of the node
node* newnode = new node();
node* nodehead = head;
newnode->data = newdata;
newnode->name = name;
newnode->right = NULL;
if( head == NULL)
{
newnode -> left = NULL;
head = tail = newnode;
}
else
{
while (nodehead->right != NULL)
{
nodehead = nodehead->right;
}
nodehead->right = newnode; // make the connection for each of them
newnode->left = nodehead;
tail = newnode; // and newly created node is our tail
sorting(newnode); // then go the function to sort them
}
cout << "New node is added " << newnode->name << " " << newnode->data << endl;
}
then sort them based on their comparison of their data and if they are equal i should check based on their alphabetical order
void sorting( node * &newnode) // ı call sorting function in the insertion function
{
node* temp = head;
node* temp2 = newnode;
int numtemp;
while (temp != nullptr)
{
node* temp2 = temp->right;
while (temp2 != nullptr)
{
if (temp2->data > temp->data) // comparison of their data if newnode's data is larger
{
string strtemp = "";
numtemp = temp->data; // Change their number
temp->data = temp2->data;
temp2->data = numtemp;
strtemp = temp->name; // Change their name
temp->name = temp2->name;
temp2->name = strtemp;
}
else if (temp2->data = temp->data) // if newly data is equal to linked list data
{
int ret;
ret = strcmp(temp2->name, temp->name); // i tried to check their string comparison but it did not work
}
temp2 = temp2->right;
}
temp = temp->right;
}
}
Your comparison operator is bad:
if(temp2->name < temp->name ) // make comparison but im not sure wheteris logical or not
{
string strtemp = "";
strtemp = temp->name; // name change
temp->name = temp2->name;
temp2->name = strtemp;
}
Should be <
.