Intersection of Two Linked Lists
2016-07-03 02:12
267 查看
Write a program to find the node at which the intersection of two singly linked lists begins.
Notice
If the two linked lists have no intersection at all, return
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.
Example
The following two linked lists:
begin to intersect at node c1.
分析:
需要先得到两个List的长度,然后让长的List先走,等到长度一致的时候,比较两个指针是否指向同一个node,如果是,返回该node。
转载请注明出处:cnblogs.com/beiyeqingteng/
Notice
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.
Example
The following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
分析:
需要先得到两个List的长度,然后让长的List先走,等到长度一致的时候,比较两个指针是否指向同一个node,如果是,返回该node。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param headA: the first list * @param headB: the second list * @return: a ListNode * cnblogs.com/beiyeqingteng */ public ListNode getIntersectionNode(ListNode h1, ListNode h2) { if (h1 == null || h2 == null) return null; int size1 = size(h1); int size2 = size(h2); for (int i = 0; i < Math.abs(size1 - size2); i++) { if (size1 > size2) { h1 = h1.next; } else { h2 = h2.next; } } while (h1 != h2) { h1 = h1.next; h2 = h2.next; } return h1; } private int size(ListNode head) { int total = 0; while (head != null) { total++; head = head.next; } return total; } }
转载请注明出处:cnblogs.com/beiyeqingteng/
相关文章推荐
- 雨
- 总结下Android中Bitmap的应用方式
- jQuery 菜单
- NodeJS学习历程(2)
- 学习JDK内置纯JAVA数据库Derby
- 重构心法——提高代码复用率
- 深度学习斯坦福cs231n 课程笔记
- 见猎心喜 浅尝辄止 偶有所得 不足为法
- 重构心法——拆分大对象
- 重构心法——你应该这样写方法
- pip常用的命令
- [转]设计模式中类的关系
- linux下合并文件夹
- java三大框架之Hibernate的个人学习
- java三大框架之Hibernate的个人学习
- java三大框架之Hibernate的个人学习
- java三大框架之Hibernate的个人学习
- ulimit命令
- Android Adapter的几个方法
- java中的匿名内部类总结