From : https://leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *index, *cur=head->next, *p, *pre;
ListNode *phead = new ListNode(0);
phead->next = head;
head->next = NULL;
while(cur) {
int val = cur->val;
pre = phead;
index = pre->next;
p = cur->next;
while(index && index->val<=val) {
pre=index;
index=index->next;
}
cur->next = index;
pre->next = cur;
cur = p;
}
head = phead->next;
delete phead;
return head;
}
};
使用插入排序算法对链表进行排序
本文介绍了一种使用插入排序算法对单链表进行排序的方法,并提供了详细的实现步骤和代码解释。
302

被折叠的 条评论
为什么被折叠?



