0

I am doing the leetcode question https://leetcode.com/problems/add-two-numbers/

Definition of a ListNode is:

 // Definition for singly-linked list.
 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

When I check if a list is hit the end, I used:

int v1 = h1 == NULL? h1->val:0; // h1 is defined before: ListNode* h1 = l1;

But it returns a runtime error, but if I changed it to

int v1 = h1? h1->val:0;

it is accepted.

Why is that?

2
  • 6
    Check that condition again... It might be clearer if you try to turn it into a normal if-else statement. Commented May 15, 2015 at 17:48
  • check out stackoverflow.com/questions/3825668/… as well. Commented May 15, 2015 at 17:50

2 Answers 2

10

This line of code:

 int v1 = h1 == NULL ? h1->val : 0;

Is more or less identical to:

int v1 = 0;
if (h1 == NULL)
    v1 = h1->val;

Note that if h1 == NULL, then you will exhibit undefined behavior when you dereference h1 in the following line.

Sign up to request clarification or add additional context in comments.

Comments

1

You need != instead of == as Null tends to be zero or false

1 Comment

Do you mean there is a logical error in that particular code, or is it a general statement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.