- 利用栈先进后出的特性,先遍历链表的元素,然后依次加入栈。
- 将所有元素加入栈中后,得到栈的长度,创建数组,弹出栈中所有元素,然后从栈中弹出元素并放如数组。
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while(temp != null){
stack.push(temp);
temp = temp.next; //指针后移
}
//链表元素全部入栈
int length = stack.size();
int[] res = new int[length];
for(int i = 0; i < length; i++){
res[i] = stack.pop().val;
}
return res;
}
}
本文地址:https://blog.csdn.net/Y_Mlsy/article/details/107288791
如对本文有疑问, 点击进行留言回复!!
现在微服务这么火,你还不了解吗?阿里P8推荐的微服务学习指南
论文笔记:SlowFast Networks for Video Recognition
网友评论