输入两个链表,找出它们的第一个公共结点。
1 public class Solution { 2 3 /** 4 * 思路:两个链表相交,存在公共的链表尾,根据链表长度的差值,移动指针,找到第一个相同的节点,即为第一个公共节点 5 * @param pHead1 6 * @param pHead2 7 * @return 8 */ 9 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { 10 11 if (pHead1 == null || pHead2 == null) { 12 return null; 13 } 14 15 int d = 0; 16 17 ListNode p1 = pHead1; 18 ListNode p2 = pHead2; 19 20 int length1 = 0; 21 while (pHead1 != null) { 22 length1++; 23 pHead1 = pHead1.next; 24 } 25 26 int length2 = 0; 27 while (pHead2 != null) { 28 length2++; 29 pHead2 = pHead2.next; 30 } 31 32 if (length1 > length2) { 33 d = length1 - length2; 34 35 while (d > 0) { 36 p1 = p1.next; 37 d--; 38 } 39 } else if (length1 < length2) { 40 d = length2 - length1; 41 42 while (d > 0) { 43 p2 = p2.next; 44 d--; 45 } 46 } else { 47 return p1; 48 } 49 50 while (p1 != null) { 51 if (p1 == p2) { 52 break; 53 } 54 p1 = p1.next; 55 p2 = p2.next; 56 } 57 return p1; 58 } 59 } 60 61 class ListNode { 62 int val; 63 ListNode next = null; 64 65 ListNode(int val) { 66 this.val = val; 67 } 68 }