Intersection of Two Linked Lists
来源:互联网 发布:怎样安装税控盘软件 编辑:程序博客网 时间:2024/05/22 15:41
这是一道补课,兼智力开发题。从最优解法中要学到以下几点:
1. 如果有相同节点链,必定存在相同结尾节点,用此可以判断最后是否存在相同节点:
if (tailA != null && tailB != null && tailA != tailB) { return null; }
2. 如果存在相同节点,且长度不同,当一个链到尾部,交换链,当另一条链到尾部,再交换,此时,两条链的指针都距离尾部相同的距离,于是可以同时前进,必能找到相同的节点。
if (p1 == null) { p1 = headB; } if (p2 == null) { p2 = headA; }3. 因为用了死循环,这个根本到不了。
//return null;
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } ListNode p1 = headA; ListNode p2 = headB; ListNode tailA = null; ListNode tailB = null; while (true) { if (p1 == null) { p1 = headB; } if (p2 == null) { p2 = headA; } if (p1.next == null) { tailA = p1; } if (p2.next == null) { tailB = p2; } if (tailA != null && tailB != null && tailA != tailB) { return null; } if (p1 == p2) { return p1; } p1 = p1.next; p2 = p2.next; } //return null; }
0 0
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Mina IoBuffer的特性介绍
- Java入门(一)——了解java、搭建开发平台
- eclipse 删除所有注释及空白行
- leetcode 25. Reverse Nodes in k-Group
- iOS —— 数据解析Null处理
- Intersection of Two Linked Lists
- MD5加盐算法(JAVA)
- Unity中网格合并示例研究。针对合并子网格列表后再合并网格
- iOS中设置百度地图自定义标注图片,自定义泡泡
- 2016年度最受欢迎的100个 Java 库
- 柴俊理金:耶伦暗示加息谨慎,原油小涨黄金承压
- hihocoder 1079离散化 java实现
- 界面延迟刷新
- Django1.96使用mysql数据库