AcWing 17. 从尾到头打印链表
作者:
枳花明
,
2024-11-20 15:00:46
,
所有人可见
,
阅读 1
①reverse做法
/**
* 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;
for( auto p=head; p; p=p->next )
{
res.push_back(p->val);
}
reverse(res.begin(),res.end());
return res;
}
};
②递归做法
class Solution {
public:
vector<int> res;
void dfs( ListNode* p )
{
if( p == NULL ) return;
dfs(p->next);
res.push_back(p->val);
}
vector<int> printListReversingly(ListNode* head) {
dfs(head);
return res;
}
};