/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
// 递归
function reverseList($head) {
if($head == null || $head->next == null) {
return $head;
}
$res = $this->reverseList($head->next);
$head->next->next = $head;
$head->next = null;
return $res;
}
// 迭代
function reverseList($head) {
if($head == null || $head->next == null) {
return $head;
}
$newHead = null;
$pre = null;
$cur = $head;
while($cur != null) {
$next = $cur->next;
if($next == null) {
$newHead = $cur;
}
$cur->next = $pre;
$pre = $cur;
$cur = $next;
}
return $newHead;
}