zoukankan      html  css  js  c++  java
  • 【leetcode】147. Insertion Sort List

    题目说明

    https://leetcode-cn.com/problems/insertion-sort-list/description/
    对链表进行插入排序。
    从第一个元素开始,该链表可以被认为已经部分排序。每次迭代时,从输入数据中移除一个元素,并原地将其插入到已排好序的链表中。

    解法1

    遍历链表,每个结点i都与前面的结点进行比较,若大于i结点,则将i结点插入到该点前面

    /*
     * 时间复杂度:O(n^2)
     * 遍历链表,每个结点i都与前面的结点进行比较,若大于i结点,则将i结点插入到该点前面
     */
    ListNode* insertionSortList(ListNode* head) {
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
    
        ListNode *pre = dummy;
        ListNode *cur = NULL;
        ListNode *next = NULL;
        ListNode *tmp = NULL;
        int flag = 0;
    
        while(pre->next){
            cur = pre->next;
            tmp = dummy;
            flag = 0;
            //从dummy->next开始遍历直到cur,找到第一个大于cur的结点
            while(tmp->next != cur){
                if (tmp->next->val > cur->val){
                    next = tmp->next;
                    tmp->next = cur;
                    pre->next = cur->next;
                    cur->next = next;
                    flag = 1;
                    break;
                }
                tmp = tmp->next;
            }
            //没有找到,则直到后移一位
            if (!flag){
                pre = pre->next;
            }
        }
        return dummy->next;
    }
    

    解法2

    对以上方法作了一些调整,基本思路一致。

    /*
     * 时间复杂度:O(n^2)
     * 遍历链表,如果当前结点i的值比后一个结点的值大,则需要排序
     * 从头结点开始遍历,找到第一个大于i结点的结点,将i结点插入到该点之前
     */
    ListNode* insertionSortList(ListNode* head) {
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
    
        ListNode *cur = head;
        ListNode *tmp = NULL;
        ListNode *findNode = NULL;
        ListNode *insertNode = NULL;
    
        while(cur){
            //当前结点的值比后一个结点的值大,则需要排序
            if (cur->next && cur->next->val < cur->val){
                insertNode = cur->next;
                findNode = dummy;
                //遍历链表,找到第一个大于目标结点的结点
                while(findNode->next && findNode->next->val < insertNode->val)
                    findNode = findNode->next;
                //将目标结点插入到该点之前
                tmp = findNode->next;
                findNode->next = insertNode;
                cur->next = insertNode->next;
                insertNode->next = tmp;
            } else
                cur = cur->next;
        }
        return dummy->next;
    }
  • 相关阅读:
    web安全性测试用例
    国内可用的网络时间服务器
    selenium需要的浏览器驱动程序下载
    杂齐杂八
    检查是否网络端口占用问题
    python入到到实战--第十章----文件
    python入到到实战--第九章
    python入到到实战--第八章
    python入到到实战--第七章
    python入到到实战--第六章
  • 原文地址:https://www.cnblogs.com/JesseTsou/p/9588674.html
Copyright © 2011-2022 走看看