getIntersectionNode 解题报告
来源:互联网 发布:mac flv 编辑:程序博客网 时间:2024/05/21 07:54
getIntersectionNode
Description
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 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.
Challenge
Your code should preferably run in O(n) time and use only O(1) memory.
实现思路
一旦两个链表出现相交,可以确定的是,从相交点往后,两个链表的长度是一样的,要找到相交点,我们可以先分别求出两个链表的长度,然后让长的先往前走几步,使两个链表剩下的长度一致,然后就可以两条同时向前遍历并进行比较节点是否相等,一旦出现相等,即为开始相交的节点,如果遍历完还没有出现相等,则说明两个链表不相交
在整个求解过程中,local和global的第i项只和第i-1项有关,所以我们可以简化local、global成两个数,具体实现如下所示:
/** * 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 */ public ListNode getIntersectionNode(ListNode headA, ListNode headB) { // Write your code here if (headA == null || headB == null) { return null; } int length1 = 1, length2 = 1; ListNode head1 = headA, head2 = headB; while (head1.next != null && head2.next != null) { head1 = head1.next; head2 = head2.next; length1++; } length2 = length1; while (head1 != null) { head1 = head1.next; length1++; } while (head2 != null) { head2 = head2.next; length2++; } while (length1 > length2) { headA = headA.next; length1--; } while (length2 > length1) { headB = headB.next; length2--; } while (headA != null && headB != null && headA != headB) { headA = headA.next; headB = headB.next; } if (headA != null && headB != null && headA == headB) { return headA; } return null; }}
0 0
- getIntersectionNode 解题报告
- 解题报告
- 解题报告
- 解题报告
- 解题报告
- 解题报告
- 解题报告
- 解题报告
- Antiprime解题报告
- expr解题报告
- 华容道解题报告
- tju解题报告
- zju1062/pku1095解题报告
- UsacoGate解题报告 --- 序曲
- ZJU 2060 解题报告
- ZJU 1331 解题报告
- ZJU 1115 解题报告
- ZJU1057解题报告
- 【清浮动的方法】
- 数据库事务和事务隔离级别
- 思考什么
- Java自带线程池和队列详细讲解
- 5-66 N个数求和 (20分)
- getIntersectionNode 解题报告
- dubbo服务端xml文件有红叉解决办法
- curl: (60) SSL certificate: unable to get local issuer certificate 解决方法
- 类似三角形数的一般推导公式
- java内存管理
- jdbc-建立与数据库的连接
- C语言计算高斯核函数
- HOJ 2662 Pieces Assignment
- Reorder array to construct the minimum number 解题报告