链表插入排序

来源:互联网 发布:淘宝aj比较靠谱的店 编辑:程序博客网 时间:2024/06/16 22:09

1.描述:

用插入排序对链表排序

样例

Given 1->3->2->0->null, return 0->1->2->3->null

2.思路:

新建一个链表,先将原链表头节点附给头节点,然后依次遍历后序节点,若节点值小于新链表的头节点就插到新链表的左边,否则插到右边。

3.代码:

ListNode *dummy=new ListNode(0);
        if(head==NULL)
        return 0;
        while(head!=NULL){
        ListNode *pre=dummy;
        while(pre->next!=NULL&&pre->next->val<head->val)
        {pre=pre->next;}
        ListNode *temp=head->next;
        head->next=pre->next;
        pre->next=head;
        head=temp;
        }
        return dummy->next;

4.感想:

这个题也讲过,照着讲的思路来就过了

0 0