【剑指offer】面试题 52. 两个链表的第一个公共结点

面试题 52. 两个链表的第一个公共结点

NowCoder

题目描述
输入两个链表,找出它们的第一个公共结点。

Java 实现
ListNode Class

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }

    @Override
    public String toString() {
        return val + "->" + next;
    }
}
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode list1 = pHead1, list2 = pHead2;
        while (list1 != list2) {
            list1 = (list1 == null) ? pHead2 : list1.next;
            list2 = (list2 == null) ? pHead1 : list2.next;
        }
        return list1;
    }
}
原文地址:https://www.cnblogs.com/hgnulb/p/10908611.html