1.求出两链表长度
2.分情况进行长链表头结点后移
3.移至相同长度,两头结点一起后移,找到公共节点
1 public class Solution { 2 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 3 4 ListNode curA = headA; 5 ListNode curB = headB; 6 int lenA = 0, lenB = 0; 7 while (curA != null) { // 求链表A的长度 8 lenA++; 9 curA = curA.next; 10 } 11 while (curB != null) { // 求链表B的长度 12 lenB++; 13 curB = curB.next; 14 } 15 curA = headA; 16 curB = headB; 17 if (lenB > lenA){ 18 int gap = lenB - lenA; 19 while (gap-- > 0) { 20 curB = curB.next; 21 } 22 while (curB != null) { 23 if (curA == curB) { 24 return curB; 25 } 26 curA = curA.next; 27 curB = curB.next; 28 } 29 30 31 } 32 33 if (lenB <= lenA){ 34 int gap = lenA - lenB; 35 while (gap-- > 0) { 36 curA = curA.next; 37 } 38 while (curA != null) { 39 if (curA == curB) { 40 return curA; 41 } 42 curA = curA.next; 43 curB = curB.next; 44 } 45 46 47 48 } 49 return null; 50 } 51 }
标签:LeetCode02.07,ListNode,next,链表,Q21,curB,curA,null From: https://www.cnblogs.com/cff1/p/18240186