两个链表的第一个公共结点

题目描述

输入两个链表,找出它们的第一个公共结点。
 
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;
    }
}
posted @ 2018-10-11 18:34  MarkLeeBYR  阅读(135)  评论(0)    收藏  举报