给定一个链表,将其倒转过来。数组
个人思路是,把每一项存进数组做为栈。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