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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
luochenhuan
  • 1,057
  • 11
  • 17

2 Answers2

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.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
1

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

Ed Heal
  • 59,252
  • 17
  • 87
  • 127