Created
August 24, 2020 05:18
-
-
Save neenjaw/4e1e3a8b6de45a29d85d09bab4ed25cc to your computer and use it in GitHub Desktop.
palindrome linked list
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 | |
* @return Boolean | |
*/ | |
function isPalindrome($head) { | |
if ($head == null) { | |
return true; | |
} | |
// Traverse the list, building a reversed list | |
$fast = $head; | |
$slow = $head; | |
$reversed = null; | |
while ($fast != null) { | |
$fast = $fast->next; | |
if ($fast != null) { | |
$fast = $fast->next; | |
$node = new ListNode($slow->val, $reversed); | |
$reversed = $node; | |
} | |
$slow = $slow->next; | |
} | |
while($slow != null) { | |
if ($slow->val != $reversed->val) { | |
return false; | |
} | |
$slow = $slow->next; | |
$reversed = $reversed->next; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment