给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
来源:力扣(LeetCode)
链接: leetcode 国内网/problems/reverse-linked-list
题解思路:正向遍历链表,反向构建新的链表。
/***
执行用时:4 ms, 在所有 PHP 提交中击败了94.30% 的用户
内存消耗:21.8 MB, 在所有 PHP 提交中击败了5.26% 的用户
通过测试用例:28 / 28
*/
/**
* Definition for a singly-linked list.
* 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)
{
return $this->reverse($head, new ListNode());
}
function reverse($list, $node)
{
$node->val = $list->val;
if (null == $list->next)
return $node;
$parent = new ListNode();
$parent->next = $node;
return $this->reverse($list->next, $parent);
}
}
