zoukankan      html  css  js  c++  java
  • 从尾到头打印链表

    【题目描述】

    输入一个链表,从尾到头打印链表每个节点的值。 
    输入描述:
    输入为链表的表头
    输出描述:
    输出为需要打印的“新链表”的表头
    【代码实现】
    实现一:基于栈的实现
     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(struct ListNode* head) {
    13         stack <struct ListNode*> nodes;
    14         struct ListNode* pNode=head;
    15         vector <int> vec;
    16         while(pNode!=NULL)
    17         {
    18             nodes.push(pNode);
    19             pNode=pNode->next;
    20         }
    21 
    22         while(!nodes.empty())
    23         {
    24             vec.push_back(nodes.top()->val);
    25             nodes.pop();
    26         }           
    27         return vec;
    28     }
    29 };

     实现二:利用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(struct ListNode* head) {
    13         struct ListNode* pNode=head;
    14         vector <int> vec;
    15        while(pNode!=NULL)
    16        {
    17            vec.insert(vec.begin(),pNode->val);
    18            pNode=pNode->next;
    19        }
    20         return vec;
    21     }
    22 };
    【点评】

        头插vector 效率太低,可以考虑替代方案:先vector.push_back 返回之前翻转vector,std::reverse(begin,end)。

    实现三:利用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(struct ListNode* head) {
    13        struct ListNode* pNode=head;
    14        vector <int> vec;
    15        while(pNode!=NULL)
    16        {
    17            vec.push_back(pNode->val);
    18            pNode=pNode->next;
    19        }  
    20        reverse(vec.begin(),vec.end());
    21        return vec;
    22     }
    23 };
  • 相关阅读:
    [USACO 5.5]Hidden Password
    [Codeforces 1016F]Road Projects
    再会,OI
    [TJOI 2018]智力竞赛
    [POI 2009]Lyz
    [NOI 2015]品酒大会
    [NOI 2017]蔬菜
    [NOI 2017]整数
    [NOI 2017]游戏
    [NOI 2017]蚯蚓排队
  • 原文地址:https://www.cnblogs.com/lou424/p/5023845.html
Copyright © 2011-2022 走看看