题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
<?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
function isPail( $head )
{
// write code here
$slow = $head;
$fast = $head;
while($fast && $fast->next){
$fast = $fast->next->next;
$slow = $slow->next;
}
$slow = reverseList($slow);
$fast = $head;
while($slow){
if($fast->val==$slow->val){
$fast = $fast->next;
$slow = $slow->next;
}else{
return false;
}
}
return true;
}
function reverseList($list){
$pre = null;
$cur = $list;
while($cur){
$next = $cur->next;
$cur->next=$pre;
$pre = $cur;
$cur = $next;
}
return $pre;
}
快慢指针找到中间节点,后半段反转,然后比较前半段和后半段值是否相同,不相同返回false
#被裁牛马刷题找工作#
查看2道真题和解析