Enter the head node of a linked list, and return the value of each node from the end to the beginning (return with an array).
Example 1:
输入:head = [1,3,2]
输出:[2,3,1]
limit:
0 <= length of linked list <= 10000
Ideas:
Traverse the linked list twice and put the value of the node backwards into the return array. The time complexity is O(N), and the space complexity is O(1).
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (head == NULL) return {
};
int len = 0;
ListNode* cur = head;
while (cur) {
len++;//计算链表长度
cur = cur->next;
}
vector<int> res(len, 0);
cur = head;
len--;
while (cur) {
res[len--] = cur->val;//反着放进数组里面
cur = cur->next;
}
return res;
}
};