148. Sort List
Question
Given a linked list header, return the sorted list in ascending order.
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = []
Output: []
Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
vectorv;
while(head){
v.push_back(head->val);
head=head->next;
}
sort(v.begin(),v.end());
ListNode*l = new ListNode(-1);
ListNode*x=l;
for(int i=0;inext = new ListNode(v[i]);
l=l->next;
}
return x->next;
}
};
Comments
Post a Comment