从尾到头打印链表(简单)
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
#include<vector>
#include<stack>
using namespace std;struct ListNode
{int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:vector<int> reversePrint(ListNode* head){vector<int> res;stack<int> s;while(head){s.push(head->val);head = head->next;}while(!s.empty()){res.push_back(s.top());s.pop();}return res;}
};
- 方法:从头到尾遍历原始链表,用栈来保存,最后弹出到向量中。
- 知识点:
- using namespace std;C++标准程序库中的所有标识符都被定义与一个名为std的namespace中;
- s.push()在栈顶增加元素;
- res.push_back()将一个新的元素加到vector最后面;
- s.top()返回栈顶元素,但不会删除栈里面的元素;
- s.pop()移除栈顶元素;