1. 程式人生 > >leetcode Intersection of Two Linked Lists

leetcode Intersection of Two Linked Lists

Intersection of Two Linked Lists 題目:https://leetcode.com/problems/intersection-of-two-linked-lists/

求兩個連結串列的交叉部分

解題思路:

1.先求兩個連結串列的長度,先讓長的連結串列移動到與短的連結串列的相同位置

2.判斷兩個連結串列的對應的元素是否相等,如果不相等,兩個連結串列同時向後移動,直到找到相同的元素。返回

如果其中有元素為null,直接返回null;

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		if(headA==null || headB==null){
			return null;
		}
		int listNodeALength = getListNodeLength(headA);
		int listNodeBLength = getListNodeLength(headB);
		int num=Math.abs(listNodeALength-listNodeBLength);
		if(listNodeALength<listNodeBLength){
			for(int i=0;i<num;i++){
				headA=headA.next;
			}
		}else{
			for(int i=0;i<num;i++){
				headB=headB.next;
			}
		}
		while(headA!=null && headB!=null && headA!=headB){
			headA=headA.next;
			headB=headB.next;
		}
		if(headA==null && headB !=null){
			return null;
		}
		if(headA!=null && headB==null){
			return null;
		}
		if(headA!=null && headB!=null && headA==headB){
			return headA;
		}
		return null;
	}
	public static  int getListNodeLength(ListNode headA){
		if(headA==null){
			return 0;
		}
		int count=0;
		while(headA!=null){
			headA=headA.next;
			count++;
		}
		return count;
	}