LeetCode OJ:Intersection of Two Linked Lists(两个链表的插入)

时间:2021-07-16 20:54:14

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3

begin to intersect at node c1.

找出第一个合并的节点的位置(或者说插入),注意复杂度为O(N),那么先遍历两个链表,求出长度,把长的那个链表前面的“剪去”,下面的就好比较了,代码如下:

 class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int len1, len2;
len1 = len2 = ;
ListNode * p = headA;
ListNode * q = headB;
while(p){
p = p->next;
len1++;
}
while(q){
q = q->next;
len2++;
}
if(len1 > len2){
int diff = len1 - len2;
while(diff--)
headA = headA->next;
}else if(len2 > len1){
int diff = len2 - len1;
while(diff--)
headB = headB->next;
}
while(headA){
if(headA == headB)
return headA;
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};