About List Null protection.

  • 1

    I noticed some codes has following protection in the beginning of the function:

    if(l1 == NULL) return l2;
    if(l2 == NULL) return l1;

    then what if both l1 and l2 are NULL? For interview purpose, should we write like following to make sure it won't return a NULL pointer, or just keep the code concise? thanks.

    if(l1 == NULL)
         if(l2 != NULL)
              return l2;
              lr = new ListCode(0);
              return lr;
    if(l2 == NULL) return l1;

  • 0

    I don't think so. It depends on your understanding what is the expected result if "exceptional input". It looks like more straight-forward if we return NULL instead of a single node with value "0" as it may represent a valid value.
    If you are a caller, I believe you are expecting a straight-forward return value to remind you the status of the function you called.

  • 0

    I think it is no need to write so many if-else to judge whether l1 or l2 is NULL and return it. We could contain the special conditions in our main loop. In my code, I use a head node to make the operation between head node and normal node same. If the l1 and l2 are both NULL, just return the head node's next -- its NULL. This is my code, any comments is welcomed.

    class Solution {
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            ListNode *sumList = new ListNode(-1);
    		ListNode *cur1 = l1, *cur2 = l2, *curSum = sumList;
    		int catching = 0;
    		while (cur1 != nullptr || cur2 != nullptr) {
    			int sum = catching;
    			if (cur1 != nullptr) {
    				sum += cur1->val;
    				cur1 = cur1->next;
    			if (cur2 != nullptr) {
    				sum += cur2->val;
    				cur2 = cur2->next;
    			sum >= 10 ? (sum -= 10, catching = 1) : (catching = 0);
    			curSum->next = new ListNode(sum);
    			curSum = curSum->next;
    		if (catching != 0) {
    			curSum->next = new ListNode(catching);
    		return sumList->next;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.