-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionNode.java
More file actions
40 lines (37 loc) · 1.07 KB
/
IntersectionNode.java
File metadata and controls
40 lines (37 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.jixue.leetcode.solutions.list;
import com.jixue.leetcode.solutions.common.list.ListNode;
/**
* Created by jx on 17/4/29.
*
* Write a program to find the node at which the intersection of two singly linked lists begins.
*For example, the following two linked lists:
<pre>
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
</pre>
* begin to intersect at node c1.
*/
public class IntersectionNode {
/**
* 需要两次循环遍历;
* 第一次遍历消除了两个链表长度的差异,第二次遍历查找相交的节点
* @param headA
* @param headB
* @return
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null){
return null;
}
ListNode currA=headA;
ListNode currB=headB;
while(currA != currB){
currA = (currA == null) ? headB : currA.next;
currB = (currB == null) ? headA : currB.next;
}
return currA;
}
}