加粗样式@TOC
反转链表
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
*/
function reverseList($head)
{
if($head == null){
return [];
}
$pre = $head;
$cru = $head->next;
$next = null;
while ($cru != null){
$next = $cru->next;
$cru->next = $pre;
$pre = $cru;
$cru = $next;
}
$head->next = null;
$head = $pre;
return $head;
}
//答案
function reverseListB($head) {
if(is_null($head) || is_null($head->next)){
return $head;
}
$pre = null;
$curr = $head;
$next = null;
while(!is_null($curr)){
$next = $curr->next;
$curr->next = $pre;
$pre = $curr;
$curr = $next;
}
return $pre;
}
}