从尾到头打印链表——C++简单易懂题解

从尾到头打印链表

http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035

O(2n)的时间复杂度和O(n)的空间复杂度解法:

  1. 先遍历一遍链表,求出链表长len。一定注意head里面也有val,坑爹的题目并没说。。。。。
  2. 申请一个长度为len的vector,i为vector从后向前存储,p为list从前向后取数
    class Solution {
    public:
     vector<int> printListFromTailToHead(ListNode* head) {
         ListNode *p = head;
         int len = 0;
         if (head == nullptr)
             return {};
         while (p != nullptr)
         {
             p = p->next;
             len++;
         }
         vector<int> res(len);
         p = head;
         for (int i = len - 1; i >= 0; i--)
         {
             res[i] = p->val;
             p = p->next;
         }
         return res;
     }
    };
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务