Created
August 24, 2020 16:03
-
-
Save neenjaw/c905f14499b080c0c43b0c3d609072c1 to your computer and use it in GitHub Desktop.
reverse Linked list II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a singly-linked list. | |
* class ListNode { | |
* public $val = 0; | |
* public $next = null; | |
* function __construct($val = 0, $next = null) { | |
* $this->val = $val; | |
* $this->next = $next; | |
* } | |
* } | |
*/ | |
class Solution { | |
/** | |
* @param ListNode $head | |
* @param Integer $m | |
* @param Integer $n | |
* @return ListNode | |
*/ | |
function reverseBetween($head, $m, $n) { | |
if ($head == null) { | |
return null; | |
} | |
$prev = null; | |
$cur = $head; | |
$count = 1; | |
// Move pointers forward until at start of range | |
while ($count < $m) { | |
$prev = $cur; | |
$cur = $cur->next; | |
$count += 1; | |
} | |
// For fixing the list references later | |
$tail = $cur; | |
$con = $prev; | |
// Step through reversing them one at a time | |
while ($count <= $n) { | |
$third = $cur->next; | |
$cur->next = $prev; | |
$prev = $cur; | |
$cur = $third; | |
$count += 1; | |
} | |
// Fix the beginning reference. | |
if ($con) { | |
// If $m != 1, ie, reversed from the middle | |
$con->next = $prev; | |
} else { | |
// If $m == 1, ie, reversed from the start | |
$head = $prev; | |
} | |
$tail->next = $cur; | |
return $head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment