Skip to content

Instantly share code, notes, and snippets.

@neenjaw
Created August 24, 2020 05:18
Show Gist options
  • Save neenjaw/4e1e3a8b6de45a29d85d09bab4ed25cc to your computer and use it in GitHub Desktop.
Save neenjaw/4e1e3a8b6de45a29d85d09bab4ed25cc to your computer and use it in GitHub Desktop.
palindrome linked 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 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