[leetCode] Intersection of Two Linked Lists
来源:互联网 发布:2016windows系统的手机 编辑:程序博客网 时间:2024/06/15 20:27
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.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; int len1 = 0, len2 = 0; ListNode tmpA = headA; while(tmpA != null) { len1++; tmpA = tmpA.next; } tmpA = headA; ListNode tmpB = headB; while(tmpB != null) { len2++; tmpB = tmpB.next; } tmpB = headB; if (len1 > len2) { for (int i = 0; i < len1 - len2; i++) { tmpA = tmpA.next; } } else if (len1 < len2) { for (int i = 0; i < len2 - len1; i++) { tmpB = tmpB.next; } } while(tmpA!= null) { if (tmpA.equals(tmpB)) return tmpA; tmpA = tmpA.next; tmpB = tmpB.next; } return tmpA; }
0 0
- [leetcode] [leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- LeetCode:Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [leetcode]Intersection of Two Linked Lists
- leetcode:Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- 【Leetcode】:Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- Copy List with Random Pointer
- 排名(杭电oj1236)(简单排序)
- What Is A CSS Reset?
- 026Java文件数据IO操作
- 如何取消WIN2008下应用报错后弹出的对话框
- [leetCode] Intersection of Two Linked Lists
- Ceilometer项目源码分析----ceilometer-alarm-notifier服务的初始化和启动
- #1066 : 无间道之并查集
- #1051 : 补提交卡
- Qt 定时器 阻塞触发容易崩溃
- C++著名类库
- 【干货】国外程序员整理的 C++ 资源大全
- 在不使用JFrame的情况下,获取鼠标桌面位置的最(zui)小(er)方法
- poj1155(树形dp)