面试题 37: 两个链表的第一个公共结点

一. 题目

输入两个链表,找出它们的第一个公共结点.

代码请到我的代码库中下载 Point2Offer

二. 代码

package week_4;

/**难度系数:***
 * 剑指offer: 两个链表的第一个公共节点
 * 方法: 两个指针
 * 测试用例:功能测试(链表有多个结点/为空/第一个公共节点为头节点/中间节点/尾结点)
 * @author dingding
 * Date:2017-7-5 21:10
 * Declaration: All Rights Reserved!
 */
public class No37 {

    public static void main(String[] args) {
        test1();
    }

    //solution
    private static ListNode findFirstCommonNode(ListNode head1,ListNode head2){
        //获取两个链表的长度
        int length1 = getListLength(head1);
        int length2 = getListLength(head2);
        int diff = length1 - length2;

        ListNode pListHeadLong = head1;
        ListNode pListHeadShort = head2;
        if (diff < 0) {
            pListHeadLong = head2;
            pListHeadShort = head1;
            diff = length2 - length1;
        }

        //在长链表中先走几步,再同时在两个链表上遍历
        for (int i=0;i<diff;i++){
            pListHeadLong = pListHeadLong.next;
        }

        while ((pListHeadLong != null) && (pListHeadShort != null) 
                && (pListHeadLong.data != pListHeadShort.data)){   //要求值相等
            pListHeadLong = pListHeadLong.next;
            pListHeadShort = pListHeadShort.next;
        }

        //得到第一个公共节点
        ListNode pFirstCommonNode = pListHeadLong;
        return pFirstCommonNode;

    }

    private static int getListLength(ListNode head) {
        int length = 0;
        ListNode pNode = head;
        while (pNode != null){
            length++;
            pNode = pNode.next;
        }
        return length;
    }

    /*===================测试用例==================*/
    private static void test1() {
        ListNode first = new ListNode(5);
        ListNode second = new ListNode(4);
        ListNode third = new ListNode(3);
        ListNode fourth = new ListNode(2);
        ListNode fifth = new ListNode(1);

        first.next = second;
        second.next = third;
        third.next =fourth;     
        fourth.next = fifth;

        ListNode head = new ListNode(7);
        ListNode first1 = new ListNode(6);
        ListNode second1 = new ListNode(8);
        ListNode third1 = new ListNode(3);
        ListNode fourth1 = new ListNode(2);
        ListNode fifth1 = new ListNode(1);

        head.next = first1;
        first1.next = second1;
        second1.next = third1;
        third1.next =fourth1;       
        fourth1.next = fifth1;

        ListNode node = findFirstCommonNode(first, head);
        if (node != null) {
            System.out.println(node.data);
        }else{
            System.out.println("NULL");
        }


    }

}



有不妥当之处,麻烦告知:D

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值