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

34次阅读

共计 549 个字符,预计需要花费 2 分钟才能阅读完成。

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;
    }
}

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

正文完
 0