206. 反转链表(reverseList)

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]

来源:力扣(LeetCode)
链接:https://leetcode.cn/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);
    }
}

 

posted @ 2022-06-27 10:10  tros  阅读(63)  评论(0)    收藏  举报