|
| 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 rotateRight($head, $k) { |
| 17 | + if($head == null){ |
| 18 | + return $head; |
| 19 | + } |
| 20 | + $k = ($k == 0) ? 0 : $k % self::getLen($head); |
| 21 | + if($k == 0){ |
| 22 | + return $head; |
| 23 | + } |
| 24 | + $head1 = self::reverse(null, $head); |
| 25 | + $dummyHead = new ListNode(0); |
| 26 | + $dummyHead->next = $head1; |
| 27 | + $cur = $dummyHead->next; |
| 28 | + $pre = $dummyHead; |
| 29 | + while($k > 0){ |
| 30 | + $pre = $cur; |
| 31 | + $cur = $cur->next; |
| 32 | + $k--; |
| 33 | + } |
| 34 | + $pre->next = null; |
| 35 | + $head2 = self::reverse(null, $cur); |
| 36 | + return self::reverse($head2, $head1); |
| 37 | + } |
| 38 | + function getLen($head){ |
| 39 | + $cnt = 0; |
| 40 | + while($head != null){ |
| 41 | + $cnt++; |
| 42 | + $head = $head->next; |
| 43 | + } |
| 44 | + return $cnt; |
| 45 | + } |
| 46 | + function reverse($pre,$head) { |
| 47 | + $tmp; |
| 48 | + $cur = $head; |
| 49 | + while($cur != null) { |
| 50 | + $tmp = $cur->next; |
| 51 | + $cur->next = $pre; |
| 52 | + $pre = $cur; |
| 53 | + $cur = $tmp; |
| 54 | + } |
| 55 | + return $pre; |
| 56 | + } |
| 57 | +} |
0 commit comments