文章目录
- Question
- Ideas
- Code
Question
输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。
数据范围
0≤ 链表长度 ≤1000。
样例
输入:[2, 3, 5]
返回:[5, 3, 2]
Ideas
Code
/**
* 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中,然后倒序输出
vector<int> res;
while(head)
{
res.push_back(head->val);
head = head -> next;
}
int len = res.size();
for (int i = 0; i < len / 2; i ++)
{
swap(res[i],res[len-i-1]);
}
return res;
}
};