leetcode147. 对链表进行插入排序

题目

插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。

实现

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

/*
类似于数组的插入排序,不同点在于数组中是从后往前遍历,链表需要从前往后遍历;数组中两元素做交换,链表中是插入和删除
1.设置虚拟头节点
2.比较两个节点compare 和 current,需要保留current的pre,next;compare的pre节点以便进行current的删除和插入
3.两个节点都涉及到前置节点,所以循环条件采用前置节点
*/
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode* pre = new ListNode(0);
        pre->next = head;
        ListNode* cur_pre = head;   
        while (cur_pre != NULL && cur_pre->next != NULL) {
            //判断cur_pre怎么变化
            int flag = 0;
            ListNode* cur = cur_pre->next;
            //当前节点的后置节点
            ListNode* cur_post = cur->next;
            ListNode* com_pre = pre;
            while (com_pre != NULL && com_pre != cur_pre) {
                ListNode* com = com_pre->next;
                if (com->val <= cur->val) {
                    com_pre = com_pre->next;
                } else {
                    cur->next = com;
                    com_pre->next = cur;
                    //这个时候cur_pre不需要移动,flag设置为1
                    flag = 1;
                    cur_pre->next = cur_post;
                    break;
                }
            }
            //flag为0,需要移动cur_pre
            if (flag == 0) {
                cur_pre = cur_pre->next;
            }
        }
        return pre->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值