问题描述
使用插入排序对链表进行排序。
解决方案
对链表插入排序。
为了方便直接插入到一个带head的空链表(带head可避免小于第一个的比较)
每次插入都是将cur节点插入到合适的位置(while中与node->next比较,找到比cur小的最大数node->val)
next保存了cur下一个要访问的节点
/**
* 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 sortList(0);
ListNode *cur = head;
while(cur){
ListNode *next = cur->next;
ListNode *node = &sortList;
while(node->next !=NULL && cur->val > node->next->val){
node = node->next;
}
cur->next = node->next;
node->next = cur;
cur = next;
}
return sortList.next;
}
};