剑指offer之从尾到头打印链表

来源:互联网 发布:工信部大数据认证 编辑:程序博客网 时间:2024/06/05 01:56

1 题目:

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

2 思路

1 从头到尾将数据存入vector<int>中,然后再将vector用reverse翻转

3 代码实现

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(ListNode* head) {        vector<int> NewList;//存放结果数据        struct ListNode* pNode=head; //指向当前节点        while(pNode!=NULL){            NewList.push_back(pNode->val);            pNode=pNode->next;        }        reverse(NewList.begin(),NewList.end());        return NewList;    }};


原创粉丝点击