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

    Sort a linked list using insertion sort.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode insertionSortList(ListNode head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(head == null) return null;
            ListNode curNode = null;
            ListNode preNode=null;
            ListNode nextNode=null;
            ListNode node = null;
            curNode = head.next;
            head.next = null;
            while(curNode!=null)//当前要插入的节点
            {
                node = curNode.next;//保存下一个节点
                if(curNode.val < head.val)//比头结点还小,则成为新的头结点
                {
                    curNode.next = head;
                    head = curNode;
                }
                else
                {
                    preNode = head;
                    nextNode = head.next;
                    while(nextNode!=null && nextNode.val<curNode.val)//找到合适位置
                    {
                        preNode = nextNode;
                        nextNode = nextNode.next;
                    }
                    curNode.next = preNode.next;
                    preNode.next = curNode;
                }
                curNode = node;
            }
            return head;//返回新的头结点
        }
    }
  • 相关阅读:
    go并发和并行
    goroutine
    go并发
    wampserver配置问题
    获取字符串的长度
    mysql中事件失效如何解决
    Go语言中Goroutine与线程的区别
    Mosquitto服务器的日志分析
    phpexcel导出数据 出现Formula Error的解决方案
    Centos6.X 手动升级gcc
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506825.html
Copyright © 2011-2022 走看看