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

    问题描述

    Sort a linked list using insertion sort.

    解决思路

    1. 设置first和last指针;

    2. 插入分三种情况。

    程序

    public class Solution {
        public ListNode insertionSortList(ListNode head) {
            ListNode dummy = new ListNode(-1);
    
            ListNode first = null, last = null;
            ListNode cur = head;
            
            while (cur != null) {
                ListNode next = cur.next; // save the next node
                cur.next = null;
                
                if (first == null || last == null) {
                    dummy.next = cur;
                    first = cur;
                    last = cur;
                } else {
                    if (cur.val <= first.val) {
                        // insert before the first
                        dummy.next = cur;
                        cur.next = first;
                        first = cur;
                    } else if (cur.val >= last.val) {
                        // insert after last
                        last.next = cur;
                        last = cur;
                    } else {
                        // find the insert place
                        ListNode node = first;
                        while (node.next != null) {
                            if (node.next.val > cur.val) {
                                break;
                            }
                            node = node.next;
                        }
                        ListNode tmp = node.next;
                        node.next = cur;
                        cur.next = tmp;
                    }
                }
                
                cur = next;
            }
    
            return first;
        }
    }
    
  • 相关阅读:
    闭包
    正则的理解
    正则
    Date对象
    math对象
    js异步
    dom事件
    事件对象-2
    事件对象
    函数作用域
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4714865.html
Copyright © 2011-2022 走看看