21.03.09 LeetCode160. 相交链表
作者:互联网
/** * 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) { //遍历AB,获得长度 int lenA=0,lenB=0; ListNode cur = headA; while(cur!=null) { lenA++; cur = cur.next; } cur = headB; while(cur!=null) { lenB++; cur = cur.next; } //获取AB的长度差 int cha = Math.abs(lenA-lenB); cur = lenA>lenB?headA:headB; ListNode c = cur==headA?headB:headA; //让长的表先走cha步 for(int i = 0;i<cha;i++) cur = cur.next; //再同时往下走 while(cur!=c && cur!=null && c!=null) { cur = cur.next; c = c.next; } return cur==null?null:cur; } }
标签:lenB,ListNode,cur,int,09,next,链表,21.03,headA 来源: https://www.cnblogs.com/pionice/p/14504348.html