Intersection of two linked lists - leetcode java
Ngày đăng:
06/12/2021
Trả lời:
0
Lượt xem:
75
Questionhttps://leetcode.com/problems/intersection-of-two-linked-lists/description/ Write a program to find the node at which the intersection of two singly linked lists begins. Example: begin to intersect at node c1. Notes:
Thought Process
Solutionpublic class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { Set set = new HashSet<>(); while (headA != null){ set.add(headA); headA = headA.next; } while (headB != null){ if (set.contains(headB)) return headB; headB = headB.next; } return null; } } public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; ListNode pA = headA, pB = headB; while (pA != pB) { pA = pA == null ? headB : pA.next; pB = pB == null ? headA : pB.next; } return pA; } }Additional |