/**
* 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;
}
};
发现顺序被打乱了,我们需要的是从后往前输出,不需要排序:
/**
* 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;
}
};