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

相關文章
相關標籤/搜索