<?php
function isPalindrome(SingleLinkedList $list)
{
if ($list->getLength() <= 0) {
return true;
}
//初始化快慢指针
$fast = $list->head->next;
$slow = $list->head->next;
$pre = null;
while ($fast != null && $fast->next != null) {
$fast = $fast->next->next; //快指针每次走两步
$tmpList = $slow->next; //临时变量保存链表
$slow->next = $pre;
$pre = $slow;
$slow = $tmpList;
}
// 链表长度为奇数的情况
if ($fast != null) {
$slow = $slow->next;
}
// 开始逐个比较
while ($slow != null) {
if ($slow->data != $pre->data) {
return false;
}
$slow = $slow->next;
$pre = $pre->next;
}
return true;
}
其中单链表的实现请移步单链表实现查看