[LeetCode][160. Intersection of Two Linked Lists] 2 Approaches: HashSet and Two Pointers with Detailed Explanation
By Long Luo
This article is the solution 2 Approaches: HashSet and Two Pointers with Detailed Explanation of Problem 160. Intersection of Two Linked Lists.
Here shows 2 Approaches to slove this problem: HashSet and Two Pointers.
HashSet
We can use to store linked list nodes.
-
Traverse the linked list , and add each node in the linked list to the ;
-
Traverse the linked list . For each node traversed, check whether the node is in the .
-
If the current node is Not in the , continue to traverse the next node;
-
If the current node is in the , then all nodes starting from the current node are in the intersection of the two linked lists. Therefore, the first node traversed in the linked list is the node intersected by the two linked lists.
-
If all the nodes in the linked list are Not in the , the two linked lists do not intersect and is returned.
-
1 | public static ListNode getIntersectionNode_hash(ListNode headA, ListNode headB) { |
Analysis
- Time Complexity:
- Space Complexity:
Two Pointers
If or is empty, they cann’t intersect each other.
If both and are not null, we can use Two Pointers and which point to the head nodes and .
Then traverse each node of and with and .
-
We needs to update the pointers and at the same time.
-
If the pointer is not null, move the pointer to the next node; If the pointer is not , move the pointer to the next node.
-
If the pointer is null, move the pointer to the head node of the linked list ; If the pointer is null, move the pointer to the head node of .
-
When the and point to the same node or both are null, return the node they point to or .
1 | public static ListNode getIntersectionNode(ListNode headA, ListNode headB) { |
Analysis
- Time Complexity:
- Space Complexity:
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗