一图胜千言,java 代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) {
return null;
}
ListNode pa = headA;
ListNode pb = headB;
while(pa != pb) {
pa = (pa == null) ? headB : pa.next; //(pa == null)判断是否到达了末尾,是则从pb的头节点开始,否则继续往后走
pb = (pb == null) ? headA : pb.next; //pa走一步之后,pb再走,这两行代码的顺序不影响结果。
}
return pa;
}
}