题目描述
编写一个程序,找到两个单链表相交的起始节点
解题思路
相交节点把两个链表分成3段,无论先后,只要把这3段都走一遍,就会碰到交点。
代码
/**
* 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 a = headA;
ListNode b = headB;
while(a != b){
a = a == null? headB : a.next;
b = b == null? headA : b.next;
}
return a;
}
}
参考:https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49785/Java-solution-without-knowing-the-difference-in-len!