从尾到头打印链表

题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
 
题解:每次插入到vector的头部直到head==NULL;
 
参考代码:
 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     {
14         vector<int> ans;
15         while(head!=NULL)
16         {
17             ans.insert(ans.begin(),head->val);
18             head=head->next;
19         }
20         return ans;
21         
22     }
23 };
View Code

 

posted @ 2019-11-27 23:23  StarHai  阅读(116)  评论(0编辑  收藏  举报