1. <?php
    2. class ListNode {
    3. public $val = 0;
    4. public $next = null;
    5. function __construct($val) { $this->val = $val; }
    6. }
    7. class Solution {
    8. /**
    9. * @param ListNode $head
    10. * @param Integer $k
    11. * @return ListNode
    12. */
    13. public function rotateRight($head, $k) {
    14. $now = $head;
    15. $length = 1;
    16. while(!is_null($now->next)) {
    17. $now = $now->next;
    18. $length++;
    19. }
    20. // 头尾相连,生成旋转链表
    21. $now->next = $head;
    22. // 注意这里的边界条件是: $length - ($k % $length)
    23. for ($i = 0; $i < $length - ($k % $length); $i++) {
    24. $head = $head->next;
    25. }
    26. $res = $head->next;
    27. $head->next = null;
    28. return $res;
    29. }
    30. }
    31. $k = 1;
    32. $head = new ListNode(1);
    33. $head->next = new ListNode(2);
    34. $head->next->next = new ListNode(3);
    35. $head->next->next->next = new ListNode(4);
    36. $head->next->next->next->next = new ListNode(5);
    37. $cls = new Solution();
    38. $r = $cls->rotateRight($head, $k);
    39. print_r($r);