Short And Easy Understand C++


  • 0
    L
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            while(headA && headB){
                if(headA->val > headB->val){
                    headB = headB->next;
                }
                else if(headA->val < headB->val){
                    headA = headA->next;
                }
                else{
                    return headA;
                }
            }
            return NULL;
        }
    };

  • 0

    I don't understand. Could you explain your idea? Is this list sorted?


  • 0
    Z

    Same question here. This should only works for sorted list.


  • 0
    L

    Whether the list is sorted, we can sure that the value of the first common node of the two linked list must be equal.


  • 0
    L

    Whether the list is sorted, we can sure that the value of the first common node of the two linked list must be equal.


  • 0
    Z

    Thanks. That's true. But what if the first nodes of the two linked lists have the same value? Say listA = [2, 3, 4, 5, 6, 7, 8, 9], listB = [2, 7, 8, 9], where the last three element "[7, 8, 9]" are the common sequence. In this case, your code should immediately return headA, which is the wrong answer.


Log in to reply
 

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