Skip to content

Instantly share code, notes, and snippets.

@neenjaw
Created August 24, 2020 15:23
Show Gist options
  • Select an option

  • Save neenjaw/180f5844b4c6f7ef50382346bf879909 to your computer and use it in GitHub Desktop.

Select an option

Save neenjaw/180f5844b4c6f7ef50382346bf879909 to your computer and use it in GitHub Desktop.
PHP reverse list
/**
* 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
* @return ListNode
*/
/* iterative solution
function reverseList($head) {
$node = $head;
$reversed = null;
while ($node != null) {
$next = $node->next;
$node->next = $reversed;
$reversed = $node;
$node = $next;
}
return $reversed;
}
*/
/* recursive solution */
function reverseList($head) {
return $this->doReverseList($head, null);
}
function doReverseList($head, $list) {
if ($head == null) {
return $list;
}
$next = $head->next;
$head->next = $list;
return $this->doReverseList($next, $head);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment