Java找出兩個鏈表的第一個公共節點

題目描述

輸入兩個鏈表,找出它們的第一個公共結點。


我的思路:因爲是鏈表,長度都是未知的,不能盲目的兩個一起開始自增判斷。

首先需要得到 L1的長度 和 L2的長度,讓較長的那個先走 (length1-length2)步。然後再一直next去判斷。

AC代碼, 34ms,503K

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
 			if(pHead1==pHead2){
                return pHead1;
            }
        
        int l1=getLength(pHead1);
        int l2=getLength(pHead2);
        if(l1>l2){
            for(int i=0;i<(l1-l2);i++){
                pHead1=pHead1.next;
            }
            
        }else{
            for(int i=0;i<(l1-l2);i++){
                pHead2=pHead2.next;
            }
        }
        
        boolean f=true;
        ListNode p=null;
        while(f){
            if(pHead1==null||pHead2==null){
                return null;
            }
            if(pHead1==pHead2){
                p=pHead1;
                f=false;
            }else{
                pHead1=pHead1.next;
                 pHead2=pHead2.next;
            }
            
        }
        
        return p;
    }
    
   
public static int getLength(ListNode pHead) {
        int length = 0;
 
        ListNode current = pHead;
        while (current != null) {
            length++;
            current = current.next;
        }
        return length;
    }
}

看看別的思路:

1、用HashMap: 

第一個while是把pHead1的所有節點都放進去。

第二個while開始,對pHead2的每個節點都用  containsKey 方法來判斷。 

因爲在前一種思路中,要求得兩個鏈表的長度就需要對兩個鏈表進行一次遍歷,用HashMap的方法其實更加節省時間。

33ms,503K

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 current1 = pHead1;
        ListNode current2 = pHead2;
 
 
        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
        while (current1 != null) {
            hashMap.put(current1, null);
            current1 = current1.next;
        }
        while (current2 != null) {
            if (hashMap.containsKey(current2))
                return current2;
            current2 = current2.next;
        }
 
        return null;
 
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章