题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int length1 = ListNodeLength(pHead1); int length2 = ListNodeLength(pHead2); if (length1 > length2) { pHead1 = WalkListNode(pHead1, length1 - length2); } else { pHead2 = WalkListNode(pHead2, length2 - length1); } while (pHead1 != null) { if (pHead1 == pHead2) return pHead1; pHead1 = pHead1.next; pHead2 = pHead2.next; } return null; } public int ListNodeLength(ListNode pHead) { int size = 0; while (pHead != null) { size++; pHead = pHead.next; } return size; } public ListNode WalkListNode(ListNode pHead, int step) { for (int i = 0; i < step; i++) { pHead = pHead.next; } return pHead; } }
计算各自链表长度以及长度差距。
共同链表节点的特点是首个节点相同,后续到尾节点的链节点都是共同的,也就是只需关心首个是否为共同节点即可。
先计算节点数量差距,去除首节点数,直到两链表相互相同数量,然后两两对比进行查找。