-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.php
51 lines (45 loc) · 1.19 KB
/
Solution.php
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
# Definition for singly-linked list.
# class ListNode {
# public $val;
# public $next;
# public function __construct($val = 0, $next = null)
# {
# $this->val = $val;
# $this->next = $next;
# }
# }
class Solution {
/**
* @param ListNode $head
* @param int $k
* @return ListNode
*/
function reverseKGroup($head, $k) {
$dummy = new ListNode(0);
$dummy->next = $head;
$prevGroupTail = $dummy;
while ($head !== null) {
$count = 0;
$groupHead = $head;
$groupTail = $head;
while ($count < $k && $head !== null) {
$head = $head->next;
$count++;
}
if ($count < $k) {
$prevGroupTail->next = $groupHead;
break;
}
$prev = null;
for ($i = 0; $i < $k; $i++) {
$next = $groupHead->next;
$groupHead->next = $prev;
$prev = $groupHead;
$groupHead = $next;
}
$prevGroupTail->next = $prev;
$prevGroupTail = $groupTail;
}
return $dummy->next;
}
}