前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指Offer-两个链表的第一个公共结点

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

作者头像
武培轩
发布2018-04-18 17:02:37
5050
发布2018-04-18 17:02:37
举报
文章被收录于专栏:武培轩的专栏武培轩的专栏
代码语言:javascript
复制
package LinkedList;

import java.util.HashMap;

/**
 * 两个链表的第一个公共结点
 * 输入两个链表,找出它们的第一个公共结点。
 */
public class Solution22 {

    public ListNode FindFirstCommonNode_2(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null)
            return null;
        ListNode current1 = pHead1;
        ListNode current2 = pHead2;

        int length1 = getLength(current1);
        int length2 = getLength(current2);
        //如果链表1的长度大于链表2的长度
        if (length1 >= length2) {
            int len = length1 - length2;
            //先遍历链表1,再遍历链表2,遍历的长度为两链表长度差
            while (len > 0) {
                current1 = current1.next;
                len--;
            }
        } else {//如果链表2的长度大于链表1的长度
            int len = length2 - length1;
            //先遍历链表2,再遍历链表1,遍历的长度为两链表长度差
            while (len > 0) {
                current2 = current2.next;
                len--;
            }
        }

        //遍历剩下节点,直到找到第一个公共节点
        while (current1 != current2) {
            current1 = current1.next;
            current2 = current2.next;
        }
        return current1;
    }

    /**
     * 获取链表长度
     *
     * @param listNode
     * @return
     */
    private int getLength(ListNode listNode) {
        int length = 0;
        while (listNode != null) {
            length++;
            listNode = listNode.next;
        }
        return length;
    }

    /**
     * 先把pHead1放入HashMap中
     * 根据HashMap的containsKey方法,查询是否有相同的节点
     *
     * @param pHead1
     * @param pHead2
     * @return
     */
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode current1 = pHead1;
        ListNode current2 = pHead2;

        HashMap<ListNode, Integer> hashMap = new HashMap<>();
        while (current1 != null) {
            hashMap.put(current1, null);
            current1 = current1.next;
        }
        while (current2 != null) {
            if (hashMap.containsKey(current2)) {
                return current2;
            }
            current2 = current2.next;
        }
        return null;
    }

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

        ListNode(int val) {
            this.val = val;
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档