Acwing 17. 从尾到头打印链表

54 阅读1分钟

17. 从尾到头打印链表 - AcWing题库

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

struct cmp
{
        bool operator()(const int& a,const int& b)
    {
        return a>b;
    }

};

    vector<int> printListReversingly(ListNode* head) {
        
        vector<int> v;
         vector<int> ans;
        while(head)
        {
            int i=0;
            v.push_back(head->val);
            head=head->next;
        }
      
      sort(v.begin(),v.end(),cmp());
      
      return v;  
    }
};

发现顺序被打乱了,我们需要的是从后往前输出,不需要排序: image.png

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

// struct cmp
// {
//         bool operator()(const int& a,const int& b)
//     {
//         return a>b;
//     }

// };

    vector<int> printListReversingly(ListNode* head) {
        
        vector<int> v;
         vector<int> ans;
        while(head)
        {
            int i=0;
            v.push_back(head->val);
            head=head->next;
        }
      
      reverse(v.begin(),v.end());
      
      return v;  
    }
};

image.png