本文共 1643 字,大约阅读时间需要 5 分钟。
题目描述
输入两个链表,找出它们的第一个公共节点。输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。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; int lenA=getLength(headA); int lenB=getLength(headB); ListNode linkLong=headA; ListNode linkedshort=headB; int diff=Math.abs(lenA-lenB); //两个链表的长度查差 if(lenB>lenA){ ListNode temp=linkLong; linkLong=linkedshort; linkedshort=temp; } //长链表先走diff步 for(int i=1;i<=diff;i++){ linkLong=linkLong.next; } //两个链表一起走, 遇到的第一个相同的节点就是所求 while(linkLong!=null && linkedshort!=null&& linkedshort!=linkLong){ linkLong=linkLong.next; linkedshort=linkedshort.next; } return linkLong; //return linkedshort一样 } public int getLength(ListNode head){ int res=0; ListNode cur=head; while(cur!=null){ res++; cur=cur.next; } return res; }}