Intersection of Two Linked Lists
2015-03-05 22:52
162 查看
编程之美上有这题,先计算这两链表的长度,然后从这两链表长度相等处扫一遍,找到相同节点就跳出即可。
O(n)的时间复杂度 O(1)的空间开销
O(n)的时间复杂度 O(1)的空间开销
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { struct ListNode *p1 = headA,*p2 = headB,*p = NULL; int lenA = 0 , lenB = 0; while(p1){ p1 = p1->next; lenA++; } while(p2){ p2 = p2->next; lenB++; } p1 = headA;p2 = headB; if(lenA>lenB){ for(int i = 0 ; i < lenA-lenB ; i++){ p1 = p1->next; } }else { for(int i = 0 ; i <lenB-lenA ; i++){ p2 = p2->next; } } for(;p1;p1 = p1->next,p2 = p2->next){ if(p1 == p2){ p = p1; break; } } return p; }
相关文章推荐
- Intersection of Two Linked Lists
- 51-Intersection of Two Linked Lists
- 160 Intersection of Two Linked Lists
- Intersection of Two Linked Lists - LeetCode
- Intersection of Two Linked Lists 查找2个链表的公共交点
- LeetCode - Intersection of Two Linked Lists
- Intersection of Two Linked Lists:寻找两个链表的交汇点
- LeetCodeOJ_160_Intersection of Two Linked Lists
- leetcode@ [160]Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- leetcode. Intersection of Two Linked Lists
- LeetCode (160) Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- 160 Intersection of Two Linked Lists
- leetcode 【 Intersection of Two Linked Lists 】python 实现
- Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- leetcode——160——Intersection of Two Linked Lists
- [leetcode]Intersection of Two Linked Lists