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

    Sort a linked list using insertion sort.

    思路: 建立一个fake head, 依次从list中取出一个node,插入到 fake head 的list中去,从小到大排列。

    public class Solution {
        public ListNode insertionSortList(ListNode head) {
            ListNode prehead = new ListNode(Integer.MIN_VALUE);
            ListNode runner = head;
            while(runner != null){
                ListNode tmp = runner.next;
                insertNode(prehead, runner);
                runner = tmp;
            }
            return prehead.next;
        }
        // 将 node 插入到fake head的list中去
        private void insertNode(ListNode head, ListNode node){
            ListNode runner = head.next;
            while(runner!=null){
                //如果当前runner node的值比 node大,将node插入
                if(runner.val >= node.val)
                    break;
                runner = runner.next;
                head = head.next;
            }
            head.next = node;
            node.next = runner;
        }
    }
  • 相关阅读:
    浅谈Semaphore类
    Python浅谈requests三方库
    191104
    191103
    191102
    191101
    191031
    191030
    191029
    191028
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3556040.html
Copyright © 2011-2022 走看看