单链表元素排序(Insertion sort list)

单链表元素排序

Sort a linked list using insertion sort. 对链表中的元素进行插入排序。


C++中使用指针的时候,一定要注意在使用指针之前要对其进行初始化,即不能让指针指向任何地方。指针一定要指向一个确定的地方。初始化如下:

ListNode *p=new ListNode; //申请一个结点p。程序会给他分配内存。

代码块

/**
* 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) {
ListNode *first=head; //用来遍历原列表
if(first==NULL)return head;
ListNode *r=new ListNode(0); //用来遍历现已排序好的列表
ListNode *pre=new ListNode(0); //用来保存插入结点时的前面一个结点 –头插法
ListNode *lis=new ListNode(0); //已排序好的列表
r->val=first->val;
r->next=NULL;

    head=r;
    while(first->next!=NULL){
        int data=first->next->val;  //插入数
        pre=r;
        bool flag=false;
        head=r;
        while(r!=NULL&&data>=r->val){  //当插入的数比后面的数还要小时  --从小到大
            pre=r;    //保存前面结点
            r=r->next;
            flag=true;
        }
        ListNode *temp=new ListNode(0);
        temp->val=data;
        if(flag==true){
            temp->next=pre->next;   //插入结点r
            pre->next=temp;
        }else{
            temp->next=pre;
            head=temp;
        }

        first=first->next;
        r=head;
    }
    return head;
}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值