Intersection of Two Linked Lists
来源:互联网 发布:sql注入绕过waf 编辑:程序博客网 时间:2024/06/05 18:59
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 {}
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
- mysql复制环境清理二进制日志
- 关于WES7的系统还原与恢复
- css3 transform 属性
- 2016.03.09-2016.03.10回顾
- iOS面试题七
- Intersection of Two Linked Lists
- css 动画 transition及animation
- 用PyMOL制作分子结构图像及所用脚本
- 同步问题
- IOS中字符串三种相加方法(转)
- [LwwtCode]24. Swap Nodes in Pairs
- 爬虫技术:(JavaScript渲染)动态页面抓取超级指南
- Android Studio添加assets文件夹
- java -abstract详解