题目描述
输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。
样例
输入:[2, 3, 5]
返回:[5, 3, 2]
算法1
反转数组
先将链表的值顺序存入到数组中,再将数组的值反转
时间复杂度 $O(n)$
C++ 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> res;
// ①先将值压入栈中
ListNode* cur = head;
while(cur != NULL){
res.push_back(cur->val);
cur = cur->next;
}
// ②将存储顺序反转
int i = 0, j = res.size() - 1;
for(; i < j; i++, j--)
swap(res[i],res[j]);
return res;
}
};