LeetCode 160: Intersection of Two Linked Lists

LeetCode 160: Intersection of Two Linked Lists

  • [LeetCode 160: Intersection of Two Linked Lists - Detailed Java Solutions](#LeetCode 160: Intersection of Two Linked Lists - Detailed Java Solutions)
    • [1. Problem Link 🔗](#1. Problem Link 🔗)
    • [2. Solution Overview 🧭](#2. Solution Overview 🧭)
    • [3. Solution 1: Two Pointers with Length Calculation (Recommended)](#3. Solution 1: Two Pointers with Length Calculation (Recommended))
      • [3.1. Algorithm](#3.1. Algorithm)
      • [3.2. Important Points](#3.2. Important Points)
      • [3.3. Java Implementation](#3.3. Java Implementation)
      • [3.4. Time & Space Complexity](#3.4. Time & Space Complexity)
    • [4. Solution 2: Two Pointers (Cycle Detection Style)](#4. Solution 2: Two Pointers (Cycle Detection Style))
      • [4.1. Algorithm](#4.1. Algorithm)
      • [4.2. Important Points](#4.2. Important Points)
      • [4.3. Java Implementation](#4.3. Java Implementation)
      • [4.4. Time & Space Complexity](#4.4. Time & Space Complexity)
    • [5. Solution 3: Hash Set Approach](#5. Solution 3: Hash Set Approach)
      • [5.1. Algorithm](#5.1. Algorithm)
      • [5.2. Important Points](#5.2. Important Points)
      • [5.3. Java Implementation](#5.3. Java Implementation)
      • [5.4. Time & Space Complexity](#5.4. Time & Space Complexity)
    • [6. Solution 4: Two Pointers with Early Termination](#6. Solution 4: Two Pointers with Early Termination)
      • [6.1. Algorithm](#6.1. Algorithm)
      • [6.2. Important Points](#6.2. Important Points)
      • [6.3. Java Implementation](#6.3. Java Implementation)
      • [6.4. Time & Space Complexity](#6.4. Time & Space Complexity)
    • [7. Solution Comparison 📊](#7. Solution Comparison 📊)
    • [8. Summary 📝](#8. Summary 📝)

LeetCode 160: Intersection of Two Linked Lists - Detailed Java Solutions

LeetCode 160: Intersection of Two Linked Lists

2. Solution Overview 🧭

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

Example:

复制代码
List A:      4 → 1 ↘
                    8 → 4 → 5
List B: 5 → 6 → 1 ↗
Output: Reference to node with value 8

Constraints:

  • If the two linked lists have no intersection, 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
  • Code should run in O(n) time and use O(1) memory

Common approaches include:

  • Two Pointers (Length Adjustment): Calculate lengths and align starting points
  • Two Pointers (Cycle Detection Style): Both pointers traverse both lists
  • Hash Set: Store visited nodes (uses O(n) space)

3. Solution 1: Two Pointers with Length Calculation (Recommended)

3.1. Algorithm

  • Calculate the lengths of both linked lists
  • Move the longer list's pointer forward by the length difference
  • Traverse both lists simultaneously until finding the intersection
  • Return the intersection node or null if no intersection

3.2. Important Points

  • Most intuitive approach
  • Easy to understand and implement
  • Guaranteed O(n) time and O(1) space

3.3. Java Implementation

java 复制代码
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        
        // Calculate lengths of both lists
        int lenA = getLength(headA);
        int lenB = getLength(headB);
        
        // Align starting points
        ListNode ptrA = headA;
        ListNode ptrB = headB;
        
        if (lenA > lenB) {
            for (int i = 0; i < lenA - lenB; i++) {
                ptrA = ptrA.next;
            }
        } else {
            for (int i = 0; i < lenB - lenA; i++) {
                ptrB = ptrB.next;
            }
        }
        
        // Traverse both lists to find intersection
        while (ptrA != null && ptrB != null) {
            if (ptrA == ptrB) {
                return ptrA;
            }
            ptrA = ptrA.next;
            ptrB = ptrB.next;
        }
        
        return null;
    }
    
    private int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            length++;
            head = head.next;
        }
        return length;
    }
}

3.4. Time & Space Complexity

  • Time Complexity: O(m + n) where m and n are list lengths
  • Space Complexity: O(1)

4. Solution 2: Two Pointers (Cycle Detection Style)

4.1. Algorithm

  • Use two pointers starting at each list's head
  • When a pointer reaches the end, redirect it to the other list's head
  • The meeting point is the intersection (or null if no intersection)
  • Mathematical proof ensures they meet at intersection point

4.2. Important Points

  • More elegant and concise
  • No need to calculate lengths
  • Clever mathematical approach

4.3. Java Implementation

java 复制代码
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        
        ListNode ptrA = headA;
        ListNode ptrB = headB;
        
        // Traverse both lists
        while (ptrA != ptrB) {
            // When ptrA reaches end, redirect to headB
            ptrA = (ptrA == null) ? headB : ptrA.next;
            // When ptrB reaches end, redirect to headA  
            ptrB = (ptrB == null) ? headA : ptrB.next;
        }
        
        return ptrA; // Either intersection node or null
    }
}

4.4. Time & Space Complexity

  • Time Complexity: O(m + n)
  • Space Complexity: O(1)

5. Solution 3: Hash Set Approach

5.1. Algorithm

  • Traverse first list and store all nodes in a hash set
  • Traverse second list and check if any node exists in the hash set
  • Return first common node found

5.2. Important Points

  • Simple to understand
  • Uses O(n) extra space
  • Good for understanding the problem

5.3. Java Implementation

java 复制代码
import java.util.HashSet;

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        
        HashSet<ListNode> visited = new HashSet<>();
        
        // Store all nodes from list A
        ListNode current = headA;
        while (current != null) {
            visited.add(current);
            current = current.next;
        }
        
        // Check list B for any common nodes
        current = headB;
        while (current != null) {
            if (visited.contains(current)) {
                return current;
            }
            current = current.next;
        }
        
        return null;
    }
}

5.4. Time & Space Complexity

  • Time Complexity: O(m + n)
  • Space Complexity: O(m) or O(n) depending on which list is stored

6. Solution 4: Two Pointers with Early Termination

6.1. Algorithm

  • Enhanced version of Solution 2
  • Add early termination if both pointers reach ends without meeting
  • Slightly more efficient in worst-case scenarios

6.2. Important Points

  • More robust implementation
  • Handles edge cases explicitly
  • Same time complexity but better constant factors

6.3. Java Implementation

java 复制代码
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        
        ListNode ptrA = headA;
        ListNode ptrB = headB;
        boolean aSwitched = false;
        boolean bSwitched = false;
        
        while (ptrA != null && ptrB != null) {
            if (ptrA == ptrB) {
                return ptrA;
            }
            
            ptrA = ptrA.next;
            ptrB = ptrB.next;
            
            // Redirect pointers when they reach ends
            if (ptrA == null && !aSwitched) {
                ptrA = headB;
                aSwitched = true;
            }
            if (ptrB == null && !bSwitched) {
                ptrB = headA;
                bSwitched = true;
            }
        }
        
        return null;
    }
}

6.4. Time & Space Complexity

  • Time Complexity: O(m + n)
  • Space Complexity: O(1)

7. Solution Comparison 📊

Solution Time Complexity Space Complexity Advantages Disadvantages
Length Calculation O(m+n) O(1) Intuitive, reliable Requires length calculation
Cycle Detection Style O(m+n) O(1) Elegant, concise Less intuitive mathematically
Hash Set O(m+n) O(m) or O(n) Simple to understand Extra space usage
Early Termination O(m+n) O(1) Robust, efficient Slightly more complex

8. Summary 📝

  • Key Insight: Two pointers can find intersection by traversing both lists in a coordinated manner
  • Recommended Approach: Solution 2 (Cycle Detection Style) is most elegant and commonly used
  • Mathematical Insight: Both pointers traverse m + n nodes total, ensuring they meet at intersection
  • Pattern Recognition: This demonstrates clever pointer manipulation in linked lists

Why Solution 2 Works:

  • Each pointer traverses: its own list + the other list
  • Total distance: m + n (same for both pointers)
  • They meet at the intersection point after covering equal distances

The cycle detection style (Solution 2) is generally preferred for interviews due to its elegance and efficiency.

相关推荐
数据大魔方7 分钟前
【期货量化实战】豆粕期货量化交易策略(Python完整代码)
开发语言·数据库·python·算法·github·程序员创富
memmolo10 分钟前
【3D传感技术系列博客】
算法·计算机视觉·3d
不爱编程爱睡觉10 分钟前
代码随想录算法训练营第四十三天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·leetcode·图论·代码随想录
六毛的毛10 分钟前
冗余连接II
算法
专注于大数据技术栈13 分钟前
java学习--Vector
java·学习
sheji341615 分钟前
【开题答辩全过程】以 基于Java的校内美食推荐系统的设计与实现为例,包含答辩的问题和答案
java·开发语言·美食
白典典18 分钟前
解决iTextPDF生成手册时目录页码与实际页码不匹配问题
java·spring·intellij-idea
静心观复21 分钟前
foreach中使用remove踩坑
java
内存不泄露21 分钟前
基于 Spring Boot 的医院预约挂号系统(全端协同)设计与实现
java·vue.js·spring boot·python·flask
永远都不秃头的程序员(互关)23 分钟前
【K-Means深度探索(二)】K值之谜:肘部法则与轮廓系数,如何选出你的最佳K?
算法·机器学习·kmeans