Sort a linked list using insertion sort.
建立一个新头结点,然后依次将head链表中的结点有序的插入到新链表中
/**
/**
* 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* vhead=new ListNode(-1);
//vhead->next=head;
ListNode* cur=head;
ListNode* pre;
while(cur !=NULL){
pre=vhead;
ListNode* tmp=cur->next;
while(pre->next!=NULL && pre->next->val <= cur->val){
pre=pre->next;
}
cur->next=pre->next;
pre->next=cur;
cur=tmp;
}
head=vhead->next;
delete vhead;
return head;
}
};
本文介绍了一种使用插入排序算法对链表进行排序的方法。首先建立一个新头结点,然后依次将原链表中的节点有序地插入到新链表中。通过遍历原链表并调整节点位置,最终实现链表的有序排列。

177

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



