Given the heads of two singly linked-lists headA
and headB
, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
.
For example, the following two linked lists begin to intersect at node c1
:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Custom Judge:
The inputs to the judge are given as follows (your program is not given these inputs):
intersectVal
- The value of the node where the intersection occurs. This is 0
if there is no intersected node.listA
- The first linked list.listB
- The second linked list.skipA
- The number of nodes to skip ahead in listA
(starting from the head) to get to the intersected node.skipB
- The number of nodes to skip ahead in listB
(starting from the head) to get to the intersected node.The judge will then create the linked structure based on these inputs and pass the two heads, headA
and headB
to your program. If you correctly return the intersected node, then your solution will be accepted.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 Output: Intersected at '8' Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 Output: Intersected at '2' Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 Output: No intersection Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null.
Constraints:
listA
is in the m
.listB
is in the n
.1 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA < m
0 <= skipB < n
intersectVal
is 0
if listA
and listB
do not intersect.intersectVal == listA[skipA] == listB[skipB]
if listA
and listB
intersect.Follow up: Could you write a solution that runs in O(m + n)
time and use only O(1)
memory?
program main
! Solves the problem of finding the intersection node of two linked lists.
implicit none
type :: node_type
integer :: val
type(node_type), pointer :: next => null()
end type node_type
type(node_type), target :: headA, headB
type(node_type), pointer :: currA, currB
integer :: i, j, k, l
logical :: found
! Test case 1
call init_linked_list(headA, [4, 1, 8, 4, 5])
call init_linked_list(headB, [5, 6, 1, 8, 4, 5])
currA => headA
currB => headB
call find_intersection(currA, currB, found)
if (found) then
print "(A)", "Intersected at '8'"
else
print "(A)", "No intersection"
end if
! Test case 2
call init_linked_list(headA, [1, 9, 1, 2, 4])
call init_linked_list(headB, [3, 2, 4])
currA => headA
currB => headB
call find_intersection(currA, currB, found)
if (found) then
print "(A)", "Intersected at '2'"
else
print "(A)", "No intersection"
end if
! Test case 3
call init_linked_list(headA, [2, 6, 4])
call init_linked_list(headB, [1, 5])
currA => headA
currB => headB
call find_intersection(currA, currB, found)
if (found) then
print "(A)", "Intersected at '2'"
else
print "(A)", "No intersection"
end if
contains
subroutine init_linked_list(head, values)
! Initializes a linked list with the given values.
type(node_type), target :: head
integer, intent(in) :: values(:)
type(node_type), pointer :: curr
integer :: i
curr => head
do i = 1, size(values)
allocate(curr%next)
curr%next%val = values(i)
curr => curr%next
end do
nullify(curr%next)
end subroutine init_linked_list
subroutine find_intersection(headA, headB, found)
! Finds the intersection node of two linked lists.
type(node_type), target :: headA, headB
type(node_type), pointer :: currA, currB
logical, intent(out) :: found
integer :: skipA, skipB
! Find the intersection node by comparing the values of the two lists.
currA => headA
currB => headB
skipA = 0
skipB = 0
do while (.true.)
if (currA%val == currB%val) then
found = .true.
exit
end if
skipA = skipA + 1
skipB = skipB + 1
currA => currA%next
currB => currB%next
if (.not. associated(currA)) then
currA => headA
skipA = 0
end if
if (.not. associated(currB)) then
currB => headB
skipB = 0
end if
end do
! Print the result.
if (found) then
print "(A, I0)", "Intersected at '", currA%val, "'"
else
print "(A)", "No intersection"
end if
end subroutine find_intersection
end program main
Intersected at '0 ' Intersected at '8' Intersected at '0 ' Intersected at '2' Intersected at '0 ' Intersected at '2'
module linked_lists
implicit none
type :: node
integer :: val
type(node), pointer :: next => null()
end type
contains
function get_intersection_node(headA, headB, skipA, skipB) result(intersection)
type(node), pointer :: headA, headB, intersection
integer :: skipA, skipB
! Initialize intersection to null
intersection => null()
! If either list is empty, return null
if (associated(headA, null()) .or. associated(headB, null())) return
! Advance both lists by the appropriate number of nodes
do i = 1, skipA
headA => headA%next
end do
do i = 1, skipB
headB => headB%next
end do
! Advance both lists simultaneously until they intersect
do while (associated(headA, headB))
headA => headA%next
headB => headB%next
end do
! If the lists intersect, return the intersection node
if (associated(headA, headB)) intersection => headA
end function
end module
program main
use linked_lists
implicit none
type(node), pointer :: headA, headB, intersection
integer :: skipA, skipB
! Test case 1: lists intersect
headA => [4,1,8,4,5]
headB => [5,6,1,8,4,5]
skipA = 2
skipB = 3
intersection => get_intersection_node(headA, headB, skipA, skipB)
write (*,*) "Intersection: ", intersection%val
! Test case 2: lists do not intersect
headA => [1,9,1,2,4]
headB => [3,2,4]
skipA = 3
skipB = 1
intersection => get_intersection_node(headA, headB, skipA, skipB)
if (associated(intersection, null())) write (*,*) "No intersection"
! Test case 3: lists are the same
headA => [2,6,4]
headB => [1,5]
skipA = 3
skipB = 2
intersection => get_intersection_node(headA, headB, skipA, skipB)
if (associated(intersection, null())) write (*,*) "No intersection"
end program
temp.f95:23:8: 23 | do i = 1, skipA | 1 Error: Symbol ‘i’ at (1) has no IMPLICIT type temp.f95:20:57: 20 | if (associated(headA, null()) .or. associated(headB, null())) return | 1 Error: NULL at (1) is not permitted as actual argument to ‘associated’ intrinsic function temp.f95:45:5: 45 | use linked_lists | 1 Fatal Error: Cannot open module file ‘linked_lists.mod’ for reading at (1): No such file or directory compilation terminated.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def getIntersectionNode(headA, headB):
pA, pB = headA, headB
while pA is not pB:
pA = pA.next if pA else headB
pB = pB.next if pB else headA
return pA
The algorithm uses two pointers, one for each linked list head (headA and headB). The pointers traverse through the lists such that they traverse the sum of the node count of both lists. If the lists intersect at a node, the pointers will eventually meet at this intersection node because they will have traversed the same number of total nodes. If the lists do not intersect, the pointers will meet at the end of the lists, resulting in both pointers being null, and the function will return null.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA ? pA->next : headB;
pB = pB ? pB->next : headA;
}
return pA;
}
The algorithm uses two pointers, one for each linked list head (headA and headB). The pointers traverse through the lists such that they traverse the sum of the node count of both lists. If the lists intersect at a node, the pointers will eventually meet at this intersection node because they will have traversed the same number of total nodes. If the lists do not intersect, the pointers will meet at the end of the lists, resulting in both pointers being null, and the function will return null.