class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<Integer>();
while(head != null){
stack.addLast(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
for(int i=0; i<stack.size(); i++){
res[i] = stack.removeLast();
}
return res;
}
}
由于stack在循环体内做pop操作,所以stack的size是发生变化的,因此不能当做循环的终止条件;正确做法应该是将res.length作为终止条件。