給定一個鏈表,將其倒轉過來。數組
個人思路是,把每一項存進數組做爲棧。this
遍歷完成後,再逐個彈出便可。.net
<?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; } }
若以爲本文章對你有用,歡迎用愛發電資助。code