1.1数组和链表:160. Intersection of Two Linked Lists(Leetcode)
来源:互联网 发布:淘宝详情图尺寸是多少 编辑:程序博客网 时间:2024/06/07 13:36
Write a program tofind the node at which the intersection of two singly linked lists begins.
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.
题目大意:给定两个链表的头节点,找出两个链表相交的节点,若没有相交节点则返回null;
先贴代码:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null) return null; //新建对象存储A,B链的末尾节点 ListNode tailA = null; ListNode tailB = null; //新建对象指向A,B链头节点 ListNode pA = headA; ListNode pB = headB; while(true){ //若遍历到链末尾,则重新从另一头开始遍历 if(pA == null){ pA = headB; } if(pB == null){ pB = headA; } //确定末尾节点位置 if(pA.next == null){ tailA = pA; } if(pB.next == null){ tailB = pB; } //如果没有相同末尾的话,则说明没有交点 if(tailA != null && tailB != null && tailA != tailB) return null; if(pA == pB) return pA;//如果在任何地方相遇,则此节点便是相交节点 pA = pA.next; pB = pB.next; } }先提一种容易想到的方法,也是博主第一时间想到的方法:
第一次遍历获得两个链表的长度,然后重新回到起点,将长的链表前移”长度差“个单位后同时遍历,每次都比较是否相等。
上述方法是在Solution里面见到的,从时间或空间复杂度来讲,两者没有明显差距,但是第二种看起来连贯且高大上,大意就是两边同时开始遍历,遍历到末尾时判断末尾节点是否相同从而判断交点是否存在,然后交换链表头继续遍历,若任何时刻两节点相等,则此节点即为解。
思路:要解决的就是长度差的问题,假设有节点,两链表长度差即为相交前的长度差,遍历速度相等的情况下,两个遍历指针同时将长短链表长度不同的地方各走一遍,即路程相等。最后得一定会同时在相交点相遇。
阅读全文
0 0
- 1.1数组和链表:160. Intersection of Two Linked Lists(Leetcode)
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode *** 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode-160. Intersection of Two Linked Lists
- LeetCode-160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode 160. Intersection of Two Linked Lists
- java 注解 反射
- 如何解决超链接被点击后hover样式不出现问题
- SDUT-3375 数据结构实验之查找三:树的种类统计
- R高水平绘图
- java和c#通过esb服务互调用组件
- 1.1数组和链表:160. Intersection of Two Linked Lists(Leetcode)
- CBK精准扶贫走进广东省暨全国代理商大会圆满落幕
- Tensorflow入门(MNIST学习)
- 欢迎使用CSDN-markdown编辑器
- Android图片放大缩小自由移动控件
- 设计23式—原型
- golang使用protobuf简易教程
- TensorFlow 辨异 —— tf.placeholder 与 tf.Variable
- 深度优先搜索(DFS)