AcWing 17. 从尾到头打印链表
原题链接
简单
作者:
Jayna_Su
,
2022-08-16 22:04:13
,
所有人可见
,
阅读 204
/**
* 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) {
// 方法1: 利用reverse函数
// vector<int> nodes;
// for (auto i = head; i; i = i->next)
// nodes.push_back(i->val);
// reverse(nodes.begin(), nodes.end());
// return nodes;
// 方法2: 反转链表试一下
vector<int> nodes;
if (!head) return nodes;
auto a = head, b = a->next;
a->next = NULL;
while (b)
{
auto tmp = b->next;
b->next = a;
a = b;
b = tmp;
}
// cout << a->val << endl;
for (auto i = a; i; i = i->next) nodes.push_back(i->val);
return nodes;
}
};