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

D78 206. Reverse Linked List

题目连接

206. Reverse Linked Listphp

题目分析

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

思路

个人思路是,把每一项存进数组做为栈。this

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

最终代码

<?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;
    }
}
复制代码

若以为本文章对你有用,欢迎用爱发电资助。.net

相关文章
相关标签/搜索