一、题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
二、代码
class Solution {
fun reversePrint(head: ListNode?): IntArray {
val stack = Stack<Int>()
var p = head
while(p != null){
stack.push(p.`val`)
p = p.next
}
val result = IntArray(stack.size)
for(index in result.indices){
result[index] = stack.pop()
}
return result
}
}
附一个大佬的解法
class Solution {
fun reversePrint(head: ListNode?): IntArray {
var curNode = head
var count = 0
while (curNode != null) {
curNode = curNode?.next
count++
}
val result = IntArray(count)
curNode = head
var index = count - 1
while (curNode != null) {
result[index] = curNode!!.`val`
curNode = curNode?.next
index--
}
return result
}
}
三、题目合集
点这里~
|