【LeetCode & 剑指offer刷题】链表题2:6 从尾到头打印链表

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

6 从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
//方法:利用栈的后进先出特性
//如果可以改变链表结构,则可以先反转链表指针,在遍历输出即可,可以不用辅助空间
class Solution
{
public:
    vector<int> printListFromTailToHead(ListNode* head)
    {
        stack<ListNode*> nodes;
        ListNode* p = head;
       
        while(p != nullptr)
        {
            nodes.push(p);
            p = p->next;
        }
       
        vector<int> result;
        while(!nodes.empty())
        {
            p = nodes.top();
            result.push_back(p->val);
            nodes.pop();
        }
        return result;
    }
};
 
 

 

posted @ 2019-01-05 16:47  wikiwen  阅读(207)  评论(0编辑  收藏  举报