LeetCode OJ:Intersection of Two Linked Lists(两个链表的插入)
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),那么先遍历两个链表,求出长度,把长的那个链表前面的“剪去”,下面的就好比较了,代码如下:
1 class Solution { 2 public: 3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 int len1, len2; 5 len1 = len2 = 0; 6 ListNode * p = headA; 7 ListNode * q = headB; 8 while(p){ 9 p = p->next; 10 len1++; 11 } 12 while(q){ 13 q = q->next; 14 len2++; 15 } 16 if(len1 > len2){ 17 int diff = len1 - len2; 18 while(diff--) 19 headA = headA->next; 20 }else if(len2 > len1){ 21 int diff = len2 - len1; 22 while(diff--) 23 headB = headB->next; 24 } 25 while(headA){ 26 if(headA == headB) 27 return headA; 28 headA = headA->next; 29 headB = headB->next; 30 } 31 return NULL; 32 } 33 };