题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2]
输出:[2,3,1]
思路:
- 递归法,每次传入head.next,以head==null为判断是否到尾部的标志,到达尾部之后,回溯,依次将head.val返回到ArrayList中,最后将集合中的元素依次复制到数组中。
时间复杂度O(n)
空间复杂度O(n)
//链表结点类
class ListNode {
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
//递归法
class Solution {
ArrayList<Integer> temp = new ArrayList();
public int[] reversePrint(ListNode head){
recall(head);
int[] result = new int[temp.size()];
for (int i = 0; i < result.length; i++){
result[i] = temp.get(i);
}
return result;
}
public void recall(ListNode head){
if(head == null) return;
recall(head.next);
temp.add(head.val);
}
}
- 栈的特点是后进先出,即最后压入栈的元素最先弹出。考虑到栈的这一特点,使用栈将链表元素顺序倒置。从链表的头节点开始,依次将每个节点压入栈内,然后依次弹出栈内的元素并存储到数组中。
时间复杂度O(n)
空间复杂度O(n)
class Solution {
public int[] reversePrint(ListNode head){
Stack<Integer> stack = new Stack();
ListNode temp = head;
while (temp != null){
stack.push(temp.val);
temp = temp.next;
}
int size = stack.size();
int[] result = new int[size];
for(int i = 0; i < size; i++){
result[i] = stack.pop();
}
return result;
}
}