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

NowCoder

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

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

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;
    }
}

相关文章:

  • 2021-06-07
  • 2021-08-19
  • 2021-07-05
  • 2022-12-23
  • 2021-05-26
  • 2021-09-08
  • 2022-12-23
  • 2021-12-24
猜你喜欢
  • 2022-03-04
  • 2021-10-11
  • 2022-12-23
  • 2021-11-21
  • 2022-01-30
相关资源
相似解决方案