牛客编程题
题目描述
输入一个链表,从尾到头打印链表每个节点的值
//思路:逆向输出,首先想到,栈的特点,它是后进先出,我们顺序遍历链表,将元素压入栈中,最后遍历完,顺序输出栈的元素,即可以实现逆序
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vs;
if (head != NULL){
stack<int> s;
ListNode* ptr = head;
while (ptr != NULL){
s.push(ptr->val);
ptr = ptr->next;
}
while(!s.empty()){
vs.push_back(s.top());
s.pop();
}
}
return vs; }};
//思路:利用vector的插入操作,iterator insert (const_iterator position, const value_type& val); 在position位置前插入val值
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vi;
while(head != NULL){
vi.insert(vi.begin(), head->val);
head = head->next;
}
return vi;
}
};