对一个链表中的节点进行插入排序
插入排序算法的视频链接及详解所示如下:
插入排序算法视频链接
LeedCode147题——对链表进行插入排序题目如下:
1.题目分析:
链表的插入排序可以分为如下三种情况:
- [1] 对节点进行头插
- [2] 对节点进行中间插入
- [3] 对节点进行尾插
1.对节点进行头插:
源代码:
ListNode* cur=head->next;
ListNode* sorthead=head;
sorthead->next=NULL;
while(cur){
ListNode* next=cur->next;
if(cur->val<=sorthead->val){
cur->next=sorthead;
sorthead=cur;
}
2. 对节点进行中间插入:
源代码:
ListNode* prev=sorthead;
ListNode* tail=sorthead->next;
while(tail){
if(cur->val<=tail->val){
cur->next=tail;
prev->next=cur;
break;
}
else{
prev=tail;
tail=tail->next;
}
}
3. 对节点进行尾插:
源代码:
ListNode* prev=sorthead;
ListNode* tail=sorthead->next;
if(tail==NULL){
prev->next=cur;
cur->next=NULL;
}
总源代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* insertionSortList(struct ListNode* head){
if(head==NULL||head->next==NULL){
return head;
}
ListNode* cur=head->next;
ListNode* sorthead=head;
sorthead->next=NULL;
while(cur){
//头插
ListNode* next=cur->next;
if(cur->val<=sorthead->val){
cur->next=sorthead;
sorthead=cur;
}
else{
ListNode* prev=sorthead;
ListNode* tail=sorthead->next;
while(tail){
//中间插入
if(cur->val<=tail->val){
cur->next=tail;
prev->next=cur;
break;
}
else{
prev=tail;
tail=tail->next;
}
}
if(tail==NULL){
//尾插
prev->next=cur;
cur->next=NULL;
}
}
cur=next;
}
return sorthead;
}
总结:
取原来无序的链表的第一个节点为头,取下一个节点与取比较,进行升序排列,注意三种情况,头插,中间插和尾插,特别是中间插和尾插,对最后一个节点的next进行置空,避免溢出。