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

    Sort a linked list using insertion sort.

    ============

    思路:

    怎么判断链表开始?   怎么判断链表结束?

    定义dummy假的头节点,这样的话直接就有了链表头dummy.next

    怎么将curr指向的节点插入到in指向的位置?

      四步就可以完成:ListNode *tmp = curr->next;//保存curr下一节点

              curr->next = in->next;//将curr节点接到in的下一位置,后指

              in->next = curr;//完成前指

              curr = tmp;//更新curr

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *findLocationInsert(ListNode *head,int x){
            for(;head->next;head = head->next){
                if(head->next->val >= x) break;
            }
            return head;
        }
        ListNode *insertionSortList(ListNode* head) {
            if(head==nullptr || head->next==nullptr) return head;
            ListNode dummy(-1);
            ListNode *curr,*in;
            curr = head;
            for(;curr;){
                in = &dummy;
                in = findLocationInsert(in,curr->val);
                ListNode *tmp = curr->next;
                curr->next = in->next;
                in->next = curr;
                curr = tmp;
            }
            return dummy.next;
        }
    };
  • 相关阅读:
    小程序排错(redis导致)
    linux系统删除-开头文件或目录
    nginx 反向代理
    memcache
    一次故障过程
    json.Decoder vs json.Unmarshal
    ssl中间证书
    作业10:String类
    Angular6如何引入jQuery-knob
    OpenJdk源码下载
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5607207.html
Copyright © 2011-2022 走看看