Skip to content

Commit 5825991

Browse files
committed
Add solution 25.
1 parent 6c9f161 commit 5825991

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Definition for a singly-linked list.
3+
* class ListNode {
4+
* public $val = 0;
5+
* public $next = null;
6+
* function __construct($val) { $this->val = $val; }
7+
* }
8+
*/
9+
class Solution {
10+
11+
/**
12+
* @param ListNode $head
13+
* @param Integer $k
14+
* @return ListNode
15+
*/
16+
function reverseKGroup($head, $k) {
17+
if($head==null || $k<2){
18+
return $head;
19+
}
20+
21+
$temp = null;
22+
$curr = $head;
23+
$prev = null;
24+
$count = 0;
25+
26+
while($count<$k && $curr!=null){
27+
$temp = $curr->next;
28+
$curr->next = $prev;
29+
$prev = $curr;
30+
$curr = $temp;
31+
$count++;
32+
}
33+
34+
if($count<$k){
35+
while($count!=0){
36+
$temp = $prev->next;
37+
$prev->next = $curr;
38+
$curr = $prev;
39+
$prev = $temp;
40+
$count--;
41+
}
42+
return $curr;
43+
}
44+
45+
$head->next = self::reverseKGroup($curr,$k);
46+
47+
return $prev;
48+
}
49+
}

0 commit comments

Comments
 (0)