AcWing 17. 从尾到头打印链表
原题链接
简单
作者:
tq
,
2024-04-11 21:26:28
,
所有人可见
,
阅读 4
//面试手撕还能写错
//第二遍基本对
//常规方法,直接对链表操作
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> res;
if(!head) return res;
if(!head -> next) {
res.push_back(head -> val);
return res;
}
auto p = head, q = p -> next;
while(q){
auto o = q -> next;
q -> next = p;
p = q, q = o;
}
head -> next = NULL;
for(auto i = p; i; i = i -> next){ //注意q已经移动到空了,链表的头是p
res.push_back(i -> val);
}
return res;
}
};
//还可以直接存储进vector,然后reverse(res.begin(), res.end())