Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.
題意:查找兩個鏈表的第一個公共節點

解題思路:公共節點以後的部分長度都是相等的,所以遍歷鏈表兩個鏈表求其長度,

遍歷鏈表A,記錄其長度lengthA,遍歷鏈表B,記錄其長度lengthB作差記爲count。

讓長的鏈表先走count步,然後兩個鏈表再同時走,直到兩個節點相同。

時間複雜度O(lengthA+lengthB),空間複雜度O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null ||headB == null)return null; 
		
		int lengthA = 1;
        int lengthB = 1;
        ListNode curNodeA = headA;
        ListNode curNodeB = headB;
        
        //遍歷鏈表A,求出鏈表A的長度
        while (curNodeA.next != null) {
			lengthA++;
			curNodeA = curNodeA.next;
		}
        //遍歷鏈表B,求出鏈表B的長度
        while (curNodeB.next != null) {
			lengthB++;
			curNodeB = curNodeB .next;
		}
        //判斷最後一個元素是否相等,若不相等,則說明沒有交
        if (curNodeA != curNodeB) {
			return null;
		}else {
			int count = Math.abs(lengthA - lengthB);
	        //重新開始
	        curNodeA = headA;
			curNodeB = headB;
	        
			if (lengthA <= lengthB) {
				while (count > 0) {
					curNodeB = curNodeB.next;
					count-- ;
				}
			} else {
				while (count > 0) {
					curNodeA = curNodeA.next;
					count--;
				}

			}
			while (curNodeA != curNodeB) {
				curNodeA = curNodeA.next;
				curNodeB = curNodeB.next;
				
			}
			//如果找到相等的,那麼返回curNodeA就是當前第一個相交的位置
			//如果遍歷到最後一個都一直不相等,那麼返回的curNodeA是尾部的null
			return curNodeA;
		}	
    }
}
注意:最後只返回curNodeA就可以了  因爲    //如果找到相等的,那麼返回curNodeA就是當前第一個相交的位置
//如果遍歷到最後一個都一直不相等,那麼返回的curNodeA是尾部的null

發佈了97 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章