Constraints of the ternary/conditional operator and recursion?

So I'm trying to replicate a c_str function, specifically strcmp, except for LinkedLists instead of char arrays. Iterating through linked lists using for loops tend to be tedious so I was going to try and use new techniques called ternary operating and recursion to perform my comparisons and iterating. As you know, strcmp returns an int; 1 if the thing you're comparing against is greater than the thing you're comparing, -1 if it's less than, 0 if it's equal.

Below is what I have so far. You can assume ListNode is your generic Linked List node class that contains information and a pointer to the next node - denoted as
'info' and 'next', respectively.

1
2
3
4
5
6
 static int compare(ListNode * L1, ListNode * L2) //bool find in notes
      {
        return L1 == NULL || L2 == NULL ? 0 : L1 -> info && L2 -> info && equal(L1->next,L2->next);
        return L1 > L2 ? 1 : L1->info && L2->info && compare(L1->next,L2->next);
        return L1 < L2 ? -1 : L1->info && L2->info && compare(L1->next,L2->next);
      }


I figured this isn't going to run how I want it to run, in fact, it'll probably only run the first return statement and ignore the other 2 completely, which leads me to my main question:

could I stuff all three conditions (equal to, greater than, less than) all into one recursive ternary operation. In other words, is there a way to write an 'else if' statement that's appended to a ternary operator?

A ternary is just an if-else statement. Yes you can embed them if you use ()
1
2
3
4
5
6
7
8
9
int main() {
  int one = 1;
  int two = 2;
  int three = 3;

  int value = three > two ? (two > three ? 4 : 5) : 2;
  cout << value << endl;
  return 0;
}
Last edited on
Exactly what I needed, thanks.
Topic archived. No new replies allowed.