剑指offer---两个链表的第一个公共结点

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

首先,想到的解题思路是:让第一个链表的每一个数和第二个链表的每一个数作比较,找出第一个相等的节点。

完整代码:

public class FindFirstCommonNode {

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        ListNode head2 = new ListNode(2);
        head2.next = new ListNode(3);
        head2.next.next = new ListNode(5);
        head2.next.next.next = new ListNode(4);

        FindFirstCommonNode(head, head2);
    }

    public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) {
            return null;
        }
        //遍历pHead1, 让他的每一个数都和pHead2比较一次
        while (pHead1 != null) {

            //pHead1当前值
            int pv1 = pHead1.val;

            //把pHead2赋给一个临时链表, 让pv1去和临时链表比较
            ListNode p2 = new ListNode(0);
            p2 = pHead2;
            while (p2 != null) {
                int pv2 = p2.val;
                if (pv1 == pv2) {
                    System.out.println(pHead1.val);
                    return pHead1;
                }
                p2 = p2.next;
            }
            pHead1 = pHead1.next;

        }
        return null;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值