File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
src/Algorithms/0025.reverse-nodes-in-k-group Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments