Check if two linked lists merge. If so, where?

后端 未结 26 1433
陌清茗
陌清茗 2020-12-07 06:43

This question may be old, but I couldn\'t think of an answer.

Say, there are two lists of different lengths, merging at a point; how do we know wher

26条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 07:37

    int FindMergeNode(Node headA, Node headB) {
      Node currentA = headA;
      Node currentB = headB;
    
      // Do till the two nodes are the same
      while (currentA != currentB) {
        // If you reached the end of one list start at the beginning of the other
        // one currentA
        if (currentA.next == null) {
          currentA = headA;
        } else {
          currentA = currentA.next;
        }
        // currentB
        if (currentB.next == null) {
          currentB = headB;
        } else {
          currentB = currentB.next;
        }
      }
      return currentB.data;
    }
    

提交回复
热议问题