码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-06-12 21:36:06      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:fir   max   head   his   pre   comm   null   class   imp   

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode head = pHead1;
        Set<ListNode> res= new HashSet<ListNode>();
        while(head!=null){
            res.add(head);
            head = head.next;
        }
        head = pHead2;
        while(head!=null){
            if(res.contains(head))
                break;
            head = head.next;
        }
        return head;
    }
}

求出两个链表长度差

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int len1=0,len2=0;
        ListNode head = pHead1;
        while(head!=null){
            len1++;
            head = head.next;
        }
        head = pHead2;
        while(head!=null){
            len2++;
            head = head.next;
        }
        ListNode maxList=null,minList=null;
        int lenc = Math.abs(len1-len2);
        if(len1>=len2){
            maxList = pHead1;
            minList = pHead2;
        }
        if(len2>len1){
            maxList = pHead2;
            minList = pHead1;
        }
        while(lenc!=0){
            maxList = maxList.next;
            lenc--;
        }
        while(maxList!=minList){
            maxList = maxList.next;
            minList = minList.next;
        }
        return maxList;
    }
}

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

标签:fir   max   head   his   pre   comm   null   class   imp   

原文地址:https://www.cnblogs.com/a1225234/p/11012629.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!