两个链表的第一个公共结点
题目描述
输入两个链表,找出它们的第一个公共结点。
Solution2: //如果两个链表长度不一样,则在循环中短链表的头部会指向长链表的头,长链表的头部会指向短链表的头。最后总会相遇
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode cur1 = pHead1;
ListNode cur2 = pHead2;
while (cur1 != cur2) {
cur1 = (cur1 == null ? pHead2 : cur1.next);
cur2 = (cur2 == null ? pHead1 : cur2.next);
}
return cur1;
}
}
浙公网安备 33010602011771号