剑指 Offer 06. 从尾到头打印链表
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while(head != null){
stack.push(head.val);
head = head.next;
}
ArrayList<Integer> list = new ArrayList<>();
while(!stack.isEmpty()){
list.add(stack.pop());
}
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); i++)
res[i] = list.get(i);
return res;
}
}
思路:
- 先将链表的值依次放入栈中
- 因为栈是先进后出的,所以在依次弹出栈中元素加入到list中
- 将list转为数组
说明:
牛客网的剑指offer中返回不是数组而是ArrayList,代码更加简单。
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>();
while(listNode != null){
stack.add(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> res = new ArrayList<>();
while(!stack.isEmpty()){
res.add(stack.pop());
}
return res;
}
}