题目
分析
全部取出来放入vector中进行排序再构造一条新链表
题解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
vector<int> ans;
if(head == NULL)
return NULL;
while(head != NULL){
ans.push_back(head->val);
head = head->next;
}
sort(ans.begin(),ans.end());
ListNode newhead(0);
ListNode *temphead = &newhead;
ListNode *p = &newhead;
for(int i=0;i<ans.size();i++){
ListNode *temp = new ListNode(ans[i]);
temphead->next = temp;
temphead = temphead->next;
}
p = p->next;
return p;
}
};