[剑指Offer] 3.从尾到头打印链表

来源:互联网 发布:js命名规范 编辑:程序博客网 时间:2024/05/19 23:10
题目描述

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

【思路】用一个vector存储,遍历链表时每次从前面插入

 1 /** 2 *  struct ListNode { 3 *        int val; 4 *        struct ListNode *next; 5 *        ListNode(int x) : 6 *              val(x), next(NULL) { 7 *        } 8 *  }; 9 */10 class Solution {11 public:12     vector<int> printListFromTailToHead(ListNode* head) {13         vector<int> S;14         ListNode* node = head;15         while(node!=NULL){16             S.insert(S.begin(),node->val);17             node = node->next;18         }19         return S;20     }21 };

 

原创粉丝点击