2019-04-01 吴亲库里 库里的深夜食堂
反转单链表

题目让我们用两种方式实现,一种迭代一种递归.遍历链表的时候,只要吧当前节点的下一个指针指向更改为它的上一个节点,更改的时候需要用另一个指针来存储下一个节点。
/**
* @param ListNode $head
* @return ListNode
*/
function reverseList($head) {
$prev=null;
$curr=$head;
while($curr !==null){
$nextcode=$curr->next;
$curr->next=$prev;
$prev=$curr;
$curr=$nextcode;
}
return $prev;
}
递归
/**
* @param ListNode $head
* @return ListNode
*/
function reverseList($head) {
if(!$head || !$head->next){
return $head;
}
$node=$this->reverseList($head->next);
$head->next->next=$head;
$head->next=null;
return $node;
}
