力扣:160_相交链表
连接:https://leetcode.cn/problems/intersection-of-two-linked-lists/description/
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
题解思路:
如果有相交,最后一个点一定相同,由此可以判断是否相交,如果是相交的把长的那个表移动到对等位置,然后headA和headB共同进步,直到两个点相同
/*** 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) {int diff=0;ListNode roota=headA;ListNode rootb=headB;while(roota.next!=null){diff++;roota=roota.next;}while(rootb.next!=null){diff--;rootb=rootb.next;}if(roota!=rootb)return null;if(diff>=0){while(diff>0){diff--;headA=headA.next;}}else{while(diff<0){headB=headB.next;diff++;}}while(headA!=headB){headA=headA.next;headB=headB.next;}return headA;}
}