-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDPP20.java
More file actions
68 lines (63 loc) · 1.71 KB
/
DPP20.java
File metadata and controls
68 lines (63 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
In this example, assume nodes with the same value are the exact same node objects.
Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
*/
/**
* 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)
{
int countA=0,countB=0;
ListNode tempA=headA, tempB=headB,startA=headA,startB=headB;
while(tempA!=null)
{
tempA=tempA.next;
countA++;
}
while(tempB!=null)
{
tempB=tempB.next;
countB++;
}
int i=0;
if(countA>countB)
{
while(i<(countA-countB))
{
startA=startA.next;
i++;
}
}
else
{
while(i<(countB-countA))
{
startB=startB.next;
i++;
}
}
int tot=0;
while(tot<Math.min(countA,countB))
{
if(startA==startB)
return startA;
startA=startA.next;
startB=startB.next;
tot++;
}
return null;
}
}