
思路一:利用栈的特性辅助求解
众所周知,栈这种数据结构的特性就是先进后出,那么我们可以先遍历链表,把链表内的数据全都push到栈里面,然后再通过pop操作获取数据放到数组里面,这样就完成了题目的要求
-
代码实现:
class Solution { public int[] reversePrint(ListNode head) { Stack<Integer> stack = new Stack<>(); while(head != null){ stack.push(head.val); head = head.next; } int[] res = new int[stack.size()]; int i = 0; while(i < res.length){ res[i] = stack.pop(); i++; } return res; } }
思路二:利用递归实现
解题思路:利用递归: 先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。这个例子充分说明了递归本质上就是一个栈,先进后出。
- 代码实现:
class Solution {
ArrayList<Integer> arr = new ArrayList<>();
public int[] reversePrint(ListNode head) {
getRes(head);
int[] intArr = arr.stream().mapToInt(Integer::intValue).toArray();
return intArr;
}
public void getRes(ListNode head){
if(head != null){
reversePrint(head.next);
arr.add(head.val);
}
}
}
网友评论