1. <?php
    2. Class ListNode {
    3. public $val = 0;
    4. public $next;
    5. public function __construct($val) {
    6. $this->val = $val;
    7. }
    8. }
    9. class Solution {
    10. public function reverseKGroup(ListNode $head, $k) {
    11. $node = $head;
    12. for($i = 0; $i < $k; $i++) {
    13. if (!$node) return $head;
    14. $node = $node->next;
    15. }
    16. $newHead = $this->reverse($head, $node);
    17. $head->next = $this->reverseKGroup($node, $k);
    18. return $newHead;
    19. }
    20. private function reverse(ListNode $start, ListNode $end) {
    21. $pre = null;
    22. while ($start !== $end) {
    23. $tmp = $start->next;
    24. $start->next = $pre;
    25. $pre = $start;
    26. $start = $tmp;
    27. }
    28. return $pre;
    29. }
    30. }
    31. $head = new ListNode(1);
    32. $head->next = new ListNode(2);
    33. $head->next->next = new ListNode(3);
    34. $head->next->next->next = new ListNode(4);
    35. $head->next->next->next->next = new ListNode(5);
    36. $cls = new Solution();
    37. $r = $cls->reverseKGroup($head, 3);
    38. print_r($r);