Created
August 24, 2020 15:23
-
-
Save neenjaw/180f5844b4c6f7ef50382346bf879909 to your computer and use it in GitHub Desktop.
PHP reverse list
This file contains hidden or 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 | |
| * @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