LeetCode -- Intersection of Two Linked Lists
2015-11-03 19:21
260 查看
题目描述:
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.
找到链表相交的节点,如果不相交返回null。
思路:
如果链表相交,设焦点为p,那么p之后的节点在链表A和链表B中必然是相同的,基于这一点:
1. 计算出链表A的长度lenA
2. 计算出链表B的长度lenB
3. 将长度长的那个链表的指针移动lenA-lenB(链表A长)或lenB-lenA(链表B长)位。
4. 同时向后移动pA(链表A指针)和pB(链表B指针),比较它们是否相等,相同则返回这个节点。
5. 直到最后都没有找到相等,则视为不相交,返回null。
实现代码:
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.
找到链表相交的节点,如果不相交返回null。
思路:
如果链表相交,设焦点为p,那么p之后的节点在链表A和链表B中必然是相同的,基于这一点:
1. 计算出链表A的长度lenA
2. 计算出链表B的长度lenB
3. 将长度长的那个链表的指针移动lenA-lenB(链表A长)或lenB-lenA(链表B长)位。
4. 同时向后移动pA(链表A指针)和pB(链表B指针),比较它们是否相等,相同则返回这个节点。
5. 直到最后都没有找到相等,则视为不相交,返回null。
实现代码:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode GetIntersectionNode(ListNode headA, ListNode headB) { var lenA = Len(headA); var lenB = Len(headB); if(lenA == 0 || lenB == 0){ return null; } var pA = headA; var pB = headB; if(lenA > lenB){ var steps = lenA-lenB; for(var i = 0;i < steps; i++){ pA = pA.next; } } else if(lenA < lenB){ var steps = lenB-lenA; for(var i = 0;i < steps; i++){ pB = pB.next; } } while(pA != null){ if(ReferenceEquals(pA , pB)){ return pA; } pA = pA.next; pB = pB.next; } return null; } private int Len(ListNode node){ var p = node; var len = 0; while(p != null){ len ++; p = p.next; } return len; } }
相关文章推荐
- zlib库 在windows下的编译与使用
- Hibernate, collections, and duplicate objects
- 问题记录
- 即时通讯-1
- Cucumber java + Webdriver (6) Cucumber的数据驱动
- Redis list 之增删改查
- 团队博客-应用功能说明书
- Repair the Wall
- LeetCode -- Course Schedule
- 第八天(练习)
- Chapter01 Scala基础知识
- LeetCode -- Binary Tree Postorder Traversal
- multipart/form-data格式上传文件
- 决策树的剪枝,分类回归树CART
- QPushbutton样式
- Javascript 面向对象编程(一):封装
- 本地yun源配置
- 移植 bash
- 条款49 了解new-handler的行为
- < !--随机数的产生 -->