输入两个链表,找出它们的第一个公共节点。
如下面的两个链表:

在节点 c1 开始相交。
解法1
/** * 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 len1=Solution.length(headA); int len2=Solution.length(headB); ListNode longList; ListNode shortList; int dis; if(len1>len2) { dis=len1-len2; longList=headA; shortList=headB; } else { dis=len2-len1; longList=headB; shortList=headA; } while(dis!=0) { longList=longList.next; dis--; } while(longList!=null) { if(longList==shortList) return longList; else { longList=longList.next; shortList=shortList.next; } } return null; } public static int length(ListNode listNode) { if(listNode==null) return 0; int sum=0; while(listNode!=null) { sum++; listNode=listNode.next; } return sum; } }
解法2
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode A=pHead1; ListNode B=pHead2; while(A!=B) { A=A==null?pHead2:A.next; B=B==null?pHead1:B.next; } return A; } }
浙公网安备 33010602011771号