-2
    /** Helper function to return the index-th node in the linked list. */
SinglyListNode* getNode(int index) {
    SinglyListNode *cur = head;
    for (int i = 0; i < index && cur; ++i) {
        cur = cur->next;
    }
    return cur;
}
/** Helper function to return the last node in the linked list. */
SinglyListNode* getTail() {
    SinglyListNode *cur = head;
    while (cur && cur->next) {
        cur = cur->next;
    }
    return cur;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
    SinglyListNode *cur = getNode(index);
    return cur == NULL ? -1 : cur->val;
}

This “ return cur == NULL ? -1 : cur->val; ”

I confused this syntax, can someone separate this sentence?

  • 1
    It is called **ternary operator** or **conditional operator**. Take a look at : http://www.cplusplus.com/articles/1AUq5Di1/ – isydmr Sep 01 '18 at 21:12

1 Answers1

0

This is a ternary operator. also known as a conditional operator.

This is used as a one liner condition statement.

this is equivalent to:

if (cur == NULL)
{
    return -1;
}
else
{
    return cur->pos;
}

please refer to the above link for more information.

Hagai Wild
  • 1,904
  • 11
  • 19
  • 1
    It is _a_ ternary operator, but more specifically it is _the_ conditional operator. And please don't post links to self-declared obsolete web pages. –  Sep 01 '18 at 21:28
  • SinglyListNode* getNode(int index) { SinglyListNode *cur = head; for (int i = 0; i < index && cur; ++i) How about i – Yuxiao Zheng Sep 01 '18 at 21:37
  • @YuxiaoZheng • A pointer has an implicit conversion to a bool. If the pointer is nullptr, it converts to false, otherwise converts to true. It looks like you could use a good introductory book to C++, here's a curated list of good C++ books: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Eljay Sep 02 '18 at 13:29