您当前的位置:首页 > 计算机 > 编程开发 > 数据结构与算法

206. 反转链表(reverseList)

时间:07-11来源:作者:点击数:
城东书院 www.cdsy.xyz

给你单链表的头节点 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);
    }
}
城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐