题目:
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 == NULL || head->next == NULL)return head;
ListNode* h = head;
ListNode* current = head->next;
h->next = NULL;
while(current != NULL) {
ListNode* next = current->next;
ListNode* sorted = head;
ListNode* past = NULL;
while(sorted != NULL && sorted->val < current->val) {
past = sorted;
sorted = sorted->next;
}
if(past == NULL) {
current->next = head;
head = current;
}
else {
past->next = current;
current->next = sorted;
}
current = next;
}
return head;
}
};