Skip to content

Instantly share code, notes, and snippets.

@neenjaw
Created August 24, 2020 16:03
Show Gist options
  • Save neenjaw/c905f14499b080c0c43b0c3d609072c1 to your computer and use it in GitHub Desktop.
Save neenjaw/c905f14499b080c0c43b0c3d609072c1 to your computer and use it in GitHub Desktop.
reverse Linked list II
/**
* 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