|
| 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 $m |
| 14 | + * @param Integer $n |
| 15 | + * @return ListNode |
| 16 | + */ |
| 17 | + function reverseBetween($head, $m, $n) { |
| 18 | + $dummy = new ListNode(-1); |
| 19 | + $pre; $cur; |
| 20 | + $connection; $tail; // tail points to the last node of the reversed sub-list |
| 21 | + $pre = $dummy; |
| 22 | + $dummy->next = $head; |
| 23 | + |
| 24 | + // this loop aims to find the connection node and the first node to be reversed. |
| 25 | + for($i=0; $i<$m-1; $i++) { |
| 26 | + $pre = $pre->next; |
| 27 | + } |
| 28 | + $connection = $pre; |
| 29 | + $tail = $cur = $pre->next; |
| 30 | + |
| 31 | + $temp; |
| 32 | + // this loop is just like the similar problem(https://leetcode.com/problems/reverse-linked-list/) |
| 33 | + for($i=$m; $i<=$n; $i++) { |
| 34 | + $temp = $cur->next; |
| 35 | + $cur->next = $pre; |
| 36 | + $pre = $cur; |
| 37 | + $cur = $temp; |
| 38 | + } |
| 39 | + |
| 40 | + // adjust the connection points |
| 41 | + $tail->next = $cur; |
| 42 | + $connection->next = $pre; |
| 43 | + return $dummy->next; |
| 44 | + } |
| 45 | +} |
0 commit comments