0、前言
本题来自 leetcode
1、题目描述
2、解题思路
如果仅仅是打印的话,可以遍历列表将元素全部压入栈中再去模拟弹栈过程,进而想到遍历链表递归实现打印。但是这道题是将链表的值反向存储在vector中返回。
所以我们需要遍历链表,将其值全部压入栈中。再将栈值全部弹出存入vector数组即可。
3、代码示例
- 栈是vector的容器适配器,vector预先分配空间可节约时间。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
// 链表值入栈
stack<int> s;
for (; head != NULL; head = head->next) {
s.push(head->val);
}
// 栈值压入动态数组
vector<int> ves(s.size());
for (int j = 0; !s.empty(); j++) {
ves[j] = s.top();
s.pop();
}
return ves;
}
};