zoukankan      html  css  js  c++  java
  • 面试题:两个链表的第一个公共节点

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

    思路1:使用HashMap很多判断重复的题都可以用HashMap

    import java.util.HashMap;
    public class Solution {
        public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            ListNode node1=pHead1;
            ListNode node2=pHead2;
            HashMap<ListNode,Integer> map=new HashMap<ListNode,Integer>();
            while(node1!=null){
                map.put(node1,null);
                node1=node1.next;
            }
            //判断Map中是否包含指定的键名
            while(node2!=null){
                if(map.containsKey(node2))  return node2;
                node2=node2.next;
            }
            return null;
        }
    }

    思路2:遍历两个链表的长度 其中一个多走k步

    public class Solution {
        public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            ListNode node1=pHead1;
            ListNode node2=pHead2;
            int length1=getLength(node1);
            int length2=getLength(node2);
            if(length1==0||length2==0) return null;
            if(length1>length2){
                int len=length1-length2;
                while(len>0){
                    len--;
                    node1=node1.next;
                }
            }else{
                int len=length2-length1;
                while(len>0){
                    len--;
                    node2=node2.next;
                }
            }
            while(node1!=node2){
                node1=node1.next;
                node2=node2.next;
            }
            return node1;
        }
        public int getLength(ListNode head){
            if(head==null) return 0;
            int length=0;
            while(head!=null){
                length++;
                head=head.next;
            }
            return length;
        }
    }
  • 相关阅读:
    Windows平板优化设置
    MAC OS UI设计
    使用bat/vbs/ahk对Windows下进行自动化操作
    C#在高性能计算领域为什么性能却如此不尽人意
    自定义多重搜索
    CF797E Array Queries
    标记永久化学习笔记
    P7200 [COCI2019-2020#1] Lutrija
    P1075 [NOIP2012 普及组] 质因数分解
    基础数论重学笔记
  • 原文地址:https://www.cnblogs.com/Aaron12/p/9540802.html
Copyright © 2011-2022 走看看