Two pointers synchronization, use "turn = l1", head does not change?


  • 0
    H

    At First, I let *head equal to *turn. I use *turn to build the new ListNode .

    Why I use "turn = l1", head does not change?

    Only using "turn->val = l1->val" can change it.

    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(!l1 && !l2)return NULL;
        ListNode *head;
    	ListNode *turn = new ListNode(0);
    	head = turn;
    	while(true){			
            if(!l1 || !l2){
                if(!l1 && l2) {turn = l2;}
    			else if(l1 && !l2) {turn = l1;}
    			break;
    		}
    		else {
    			if(l1->val > l2->val){
    				turn->val = l2->val;
    				l2 = l2->next;
    			}
    			else {
    				turn->val = l1->val;
    				l1 = l1->next;
    			}
    		}
    		turn->next = new ListNode(0);
    		turn = turn->next;
    	}
    	return head;
    }

Log in to reply
 

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