avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home Leetcode-Intersection of Two Linked Lists LCCI
文章

Leetcode-Intersection of Two Linked Lists LCCI

Posted 2022-07-15
4~5 min read

Intersection of Two Linked Lists LCCI

leetcode: https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/

Description:

Given two (singly) linked lists, determine if the two lists intersect. Return the inter­ secting node. Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting.

Idea:

**solution **

Step1: create the set to record unique elements of one list

Step2: create index to traverse two list, in the first list, add all elements to set. in the loop of second list, check the node of list exists in the set or not, if exists return the node.

Step3: if no intersection, return null.

Code:

/**
 * 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) {
        //create index to traverse two list
        ListNode a = headA;
        ListNode b = headB;
        //create the set to record node
        Set<ListNode> record = new HashSet<>();
        //add node to set
        while(a != null){
            record.add(a);
            a = a.next;
        }
        //if the node in b exists in the set, it means there exists intersect
        while(b != null){
            if(record.contains(b)){
                return b;
            }
            b = b.next;
        }
        return null;
    }
}
Leetcode
Leetcode Linked List
Share

Further Reading

Apr 23, 2025

283 - Move Zero

[283 - Move Zero] 🔗 LeetCode Link Problem Description Given an integer array nums, move all 0's to the end of it while maintaining the relative order

Apr 23, 2025

27 - Remove Element

[27 - Remove Element] 🔗 LeetCode Link Problem Description Given an integer array nums and an integer val, remove all occurrences of val in nums in-pl

Apr 23, 2025

26 - Remove Duplicates from Sorted Array

[26 - Remove Duplicates from Sorted Array] 🔗 LeetCode Link Problem Description Given an integer array nums sorted in non-decreasing order, remove the

OLDER

Leetcode-19-Remove Nth Node From End of List

NEWER

Leetcode-142-Linked List Cycle II

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Here’s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents