Leetcode PHP题解--D78 206. Reverse Linked List


D78 206. Reverse Linked List

题目链接

206. Reverse Linked List

题目分析

给定一个链表,将其倒转过来。

思路

我的思路是,把每一项存进数组作为栈。

遍历完成后,再逐个弹出即可。

最终代码

<?php
/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {
    /**
     * @param ListNode $head
     * @return ListNode
     */
    function reverseList($head) {
        $stack = [];
        while(true){
            $stack[] = $head;
            $head = $head->next;
            if(is_null($head)){
                break;
            }
        }
        $root = $head = array_pop($stack);
        while($stack){
            $head->next = array_pop($stack);
            $head = $head->next;
        }
        $head->next = null;
        return $root;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D77 812. Largest Triangle Area

>> 下一篇: Nginx 通过反向代理在多个平台接入上游的客户信息