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

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;
    }
}
posted @ 2019-06-12 20:44  御心飞行  阅读(458)  评论(0编辑  收藏  举报