Intersection of Two Linked Lists
2016-03-11 10:37
225 查看
160. Intersection of Two Linked Lists
My SubmissionsQuestion
Total Accepted: 65866 Total
Submissions: 218868 Difficulty: Easy
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.
双指针法 pa, pb
遍历链表A,记录其长度lengthA,遍历链表B,记录其长度lengthB。
因为两个链表的长度可能不相同,比如题目所给的case,lengthA=5,lengthB=6,则作差得到 lengthB- lengthA=1,将指针pb从链表B的首节点开始走1步,即指向了第二个节点,pa指向链表A首节点,然后它们同时走,每次都走一步,当它们相等时,就是交集的节点。
时间复杂度O(lengthA+lengthB),空间复杂度O(1)。双指针法的代码如下:
/** * Created by jason on 2016/3/11. */ class Solution75 { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; ListNode pa = headA; ListNode pb = headB; int lengthA=0, lengthB=0; while (pa != null) { pa = pa.next; lengthA++; } while (pb != null) { pb = pb.next; lengthB++; } if (lengthA <= lengthB) { int n = lengthB - lengthA; pa = headA; pb = headB; while (n != 0) { pb = pb.next; n--; } }else { int n = lengthA - lengthB; pa = headA; pb = headB; while (n!=0) { pa = pa.next; n--; } } while (pa != pb) { pa = pa.next; pb = pb.next; } return pa; } } public class LC75 { }
相关文章推荐
- java基础之反射
- Ubuntu 12.04之找不到Qemu命令
- 【转】jbdc程序启动报错:ORA-12505;PL/SQL却可以登录的解决方法
- svn在linux上的安装
- 合唱队
- play 部署问题 play.exceptions.TemplateExecutionException: No signature of method: java.lang.String.f
- 用PyMOL制作分子结构图像及所用脚本
- bzoj 2301: [HAOI2011] Problem b
- JAVA总结知识点(一)
- IOS中字符串三种相加方法(转)
- 解决matplotlib中文乱码问题
- 次方求模
- 同步问题
- 全志a20 支持fb0 终端内容显示
- 安卓按home键之后,再次点击程序图标避免再次重新启动程序解决办法
- mysql复制环境清理二进制日志
- [LwwtCode]24. Swap Nodes in Pairs
- html嵌入js代码显示而不执行的
- document.documentElement.scrollTop(获取滚动条位置)
- 只有高中学历的我是怎样加入谷歌的?