-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersectionOfTwoLinkedLists.php
More file actions
74 lines (52 loc) · 1.12 KB
/
intersectionOfTwoLinkedLists.php
File metadata and controls
74 lines (52 loc) · 1.12 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
69
70
71
72
73
74
<?php
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
/**
* @param ListNode $headA
* @param ListNode $headB
* @return ListNode
*/
function getIntersectionNode($headA, $headB) {
$pA = $headA;
$pB = $headB;
$a_len = getNodeListLength($pA);
$b_len = getNodeListLength($pB);
$len = abs($a_len - $b_len);
if($a_len >= $b_len){
//A链表较长,则A链表指针先移动$a_len-$b_len位
while ($len > 0){
$pA = $pA->next;
$len--;
}
}else{
//同理则B链表先移动
while ($len > 0){
$pB = $pB->next;
$len--;
}
}
while($pA !== null && $pB !== null && $pA !== $pB){
$pA = $pA->next;
$pB = $pB->next;
}
if($pA === null || $pB ===null){
return null;
}else{
return $pA;
}
}
function getNodeListLength($head)
{
$i = 0;
while ($head !== null){
$head = $head->next;
$i++;
}
return $i;
}