一:问题描述
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
二:问题分析
设PA指针从A链表从头遍历到尾,然后再从B的头部开始遍历到A和B相交节点的距离为DISTANCE(PA);
设PB指针从B链表从头遍历到尾,然后再从A的头部开始遍历到A和B相交节点的距离为DISTANCE(PB);
则有DISTANCE(PA)==DISTANCE(PB)。
所以这道题可以用双指针进行解决。
三:问题求解
/**
* 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 pointerA=headA;
ListNode pointerB=headB;
while(pointerA!=pointerB){
pointerA=pointerA==null?headB:pointerA.next;
pointerB=pointerB==null?headA:pointerB.next;
}
return pointerA;
}
}