輸入兩個鏈表,找出它們的第一個公共結點(Java)算法總結

package Tree;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
 }

public class sharePoint {

	//運用HashMap的特性
	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(key, value);
			hashMap.put(current1, null);
			current1 = current1.next;
		}
		while(current2 !=null){
			if(hashMap.containsKey(current2))
				return current2;
			current2 = current2.next;
		}
		
		return null;
	}
	
	//HashSet集合
	public ListNode FindFirstCommonNode3(ListNode pHead1, ListNode pHead2) {
		
		ListNode current1 = pHead1;
		ListNode current2 = pHead2;
		HashSet<ListNode> hashSet = new HashSet<ListNode>();
		while (current1 != null) {
		hashSet.add(current1);
		current1 = current1.next;
		}
		while (current2 != null) {
		if (hashSet.contains(current2))
		return current2;
		current2 = current2.next;
		}
		return null; 
	}
 
	//stack	
	public ListNode FindFirstCommonNode4(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null||pHead2==null){
            return null;
        }
        Stack<ListNode> s1 = new Stack<ListNode>();
        Stack<ListNode> s2 = new Stack<ListNode>();
 
        while(pHead1!=null){
            s1.push(pHead1);
            pHead1 = pHead1.next;
        }
        while(pHead2!=null){
            s2.push(pHead2);
            pHead2 = pHead2.next;
        }
        ListNode firstNode = null;
        while(!s1.isEmpty()&&!s2.isEmpty()&&s1.peek()==s2.peek()){
            s1.pop();
            firstNode=s2.pop();
        }
        return firstNode;
    }
	
	// 鏈表遍歷,存在疑問
	public static int getLength(ListNode p){
		int len=0;
		while(p!=null){
			p = p.next;
			len++;
		}
		return len;
	}
	public ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
		//ListNode p1 = pHead1;    ListNode p2 = pHead2;
		//int len1 = getLength(p1);    int len2 = getLength(p2);

		int leng = getLength(pHead1)-getLength(pHead1);
		if(leng>0){
			while(leng>=0){
				pHead1 = pHead1.next;
				leng--;
			}
			while(pHead1!=pHead2){
				pHead1 = pHead1.next;
				pHead2 = pHead2.next;
			}
			return pHead1;
			
		}
		if(leng<=0){
			while(leng>=0){
				pHead2 = pHead2.next;
				leng++;
			}
		
			while(pHead2!=pHead1){
				pHead2 = pHead2.next;
				pHead1 = pHead1.next;
			}
			return pHead2;
		 }
	
 	    return null;
	}
}

 

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