AcWing 17. 用Stack从尾到头打印链表
原题链接
简单
作者:
Leo_88
,
2021-02-25 21:41:18
,
所有人可见
,
阅读 316
1. 用Stack容器实现
/**
* 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;
stack <struct ListNode*> S; //创建一个stack来存放节点地址(LIFO!)
ListNode *temp = head;
while(temp!=NULL){
S.push(temp);
temp = temp->next;
}
while (!S.empty()) {
res.push_back(S.top()->val);
S.pop();
}
return res;
}
};
2. 用Vector容器实现
1. 调用(rbegin(), rend()) 也可以遍历再reverse vector容器
/**
* 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;
while (head) {
res.push_back(head->val);
head = head->next;
}
return vector<int>(res.rbegin(), res.rend());
}
};