Question

I have a program which places structures in a linked list based on the 'name' they have stored in them.

To find their place in the list, i need to figure out if the name im inserting is earlier or later in the alphabet then those in the structures beside it.

The names are inside the structures, which i have access to. I don't need a full comaparison if that is more work, even just the first letter is fine.

Thanks for the help!

Was it helpful?

Solution

It's not clear to me what your question is, but something like this would work:

if (node1->name[0] <= node2->name[0]) {
  ...
} else {
  ...
}

This will compare the first letter of the name in each of the nodes.

OTHER TIPS

If you have two C strings, a and b, you can simply compare their first elements:

*a == *b

Where == can be any of the six relational operators.

Remember that with C strings, the char* points to the first character in the string.

strcmp() compares two C strings and will tell you what order they're in, or if they're the same. If you don't care about case, you can use strcasecmp(). These functions won't compare any more of the strings than necessary to determine what order to return.

You can simply iterate through the list and insert the new element in the correct place based on comparisons you do while passing each element. The simplest case sensitive version can be done just by comparing the numeric values of the letters (e.g. a[0] < b[0]), or you can convert both to a common case if you want to be case-insensitive (see ctype.h). Or you can compare the whole words with strcmp.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top