-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetKthFromEnd.php
More file actions
56 lines (37 loc) · 742 Bytes
/
getKthFromEnd.php
File metadata and controls
56 lines (37 loc) · 742 Bytes
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
<?php
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
/**
* @param ListNode $head
* @param Integer $k
* @return ListNode
*/
function getKthFromEnd($head, $k) {
if($head === null || $head->next === null){
return null;
}
$cur = $head;
$count = 0;
while ($cur != null){
$cur = $cur->next;
$count++;
}
if($k > $count){
return null;
}
$break_num = $count - $k;
$cur = $head;
while ($cur != null){
if($break_num == 0){
return $cur;
}
$break_num--;
$cur = $cur->next;
}
}