题目描述

输入一个链表,从尾到头打印链表每个节点的值。

 

思路:利用栈的入栈性质,把链表的数都压栈。然后出栈,把所有出栈的数添加到vector中,最后返回vector。 

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
       stack<int>temp;
        vector<int>res;
        while(head){
            temp.push(head->val);
            head=head->next;
        }
        while(temp.size()){
            res.push_back(temp.top());
            temp.pop();
        }
        return res; 
    }
};

  

关于不太了解stack、vector中push、push_back性质的可以查阅如下博客。

http://blog.csdn.net/wangdd_199326/article/details/76574142

 

参考网上的另外一种思路:用库函数,每次扫描一个节点,将该结点数据存入vector中,如果该节点有下一节点,将下一节点数据直接插入vector最前面,直至遍历完,或者直接加在最后,最后调用reverse

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> value;
        if(head != NULL)
        {
            value.insert(value.begin(),head->val);
            while(head->next != NULL)
            {
                value.insert(value.begin(),head->next->val);
                head = head->next;
            }         
             
        }
        return value;
    }
};

  

posted on 2017-08-02 12:44  王小东大将军  阅读(151)  评论(0编辑  收藏  举报