• 面试题:两个链表的第一个公共节点


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

    思路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;
        }
    }
  • 相关阅读:
    MySQL索引底层数据结构
    numpy和matplotlib读书笔记
    Python turtle学习笔记 #11933
    turtle笔记
    五角星绘制
    六角形绘制
    叠加等边三角形绘制
    什么叫方法签名
    Java编程思想 第七章
    类加载机制
  • 原文地址:https://www.cnblogs.com/Aaron12/p/9540802.html
Copyright © 2020-2023  润新知