问题:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2]
输出:[2,3,1]
解答:
/**
* Definition for singly-linked list.
* class ListNode(var _x: Int = 0) {
* var next: ListNode = null
* var x: Int = _x
* }
*/
import scala.collection.mutable
object Solution {
def reversePrint(head: ListNode): Array[Int] = {
var temp = new mutable.ArrayStack[Int]()
var temp1 = head
var length = 0
while(temp1 != null){
temp.push(temp1.x)
temp1 = temp1.next
length += 1
}
val array = new Array[Int](length)
for(i <- 0 until length){
array(i) = temp.pop()
}
return array
}
}
思路:从尾到头打印链表,利用栈的先进后出,遍历链表存入栈中,然后将栈中元素弹出至数组。