题目描述
给定一个无序单链表,实现单链表的选择排序(按升序排序)。
示例1
输入
[1,3,2,4,5]
输出
{1,2,3,4,5}
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* getSmallLeastPreNode(ListNode* head){
ListNode* small = head;
ListNode* smallPre = NULL;
ListNode* cur = head->next;
ListNode* pre = head;
while(cur!=NULL){
if(cur->val < small->val){
smallPre = pre;
small = cur;
}
pre = cur;
cur = cur->next;
}
return smallPre;
}
ListNode* sortInList(ListNode* head) {
// write code here
ListNode* tail = NULL;
ListNode* cur = head;
ListNode* smallPre = NULL;
ListNode* small = NULL;
while(cur!=NULL){
small = cur;
smallPre = getSmallLeastPreNode(cur);
if(smallPre!=NULL){
small = smallPre->next;
smallPre->next = small->next;
}
cur = cur==small?cur->next:cur;
if(tail==NULL){
head = small;
}else{
tail->next = small;
}
tail = small;
}
return head;
}
};