java:
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> tem = new LinkedList<>();
while (head != null) {
tem.addLast(head.val);
head = head.next;
}
int[] res = new int[tem.size()];
int size = tem.size();//size不能放在for循环中!!
for (int i = 0; i < size; i++) {
res[i] = tem.removeLast();//removeLast会返回值,不用先get
}
return res;
}
}
cpp:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution{
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> Result;
stack<int> st;
//第一步遍历链表存入栈
while (head != NULL) {
st.push(head->val);
head = head->next;
}
//第二步出栈存入数组
while (!st.empty()) {
Result.push_back(st.top());
st.pop();
}
return Result;
}
};