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;
        }
    }
  • 相关阅读:
    N个数求和(PTA)
    集合相似度(PTA)
    方格取数(1)(状压dp入门)
    Drainage Ditches(dinic模板)
    The Accomodation of Students(二分图判断+匈牙利算法)
    Gopher II(匈牙利算法模板)
    Apple Tree(树状数组)
    node.js中的文件系统
    canvas简易画板
    canvas绘制爱心的几种方法
  • 原文地址:https://www.cnblogs.com/Aaron12/p/9540802.html
Copyright © 2011-2022 走看看