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

    Question:

    Sort a linked list using insertion sort.

    Tips:

    使用插入排序,对一个链表进行排序。

    思路:

    新建一个头结点newHead,设置一个pre指针,指向newHead。

    cur指针,指向原来的头结点head。

    当pre.next的值大于cur的值,就将cur插入到pre之后,否则pre指针后移。

    插入一个值之后再将pre指向newHead。

    代码:

    public ListNode insertionSortList(ListNode head) {
             if(head==null ||head.next==null) return head;
             //新的头结点
                ListNode newHead= new ListNode(-1);
                ListNode pre=newHead;
                ListNode cur=head;
                ListNode next=null;
                while(cur!=null){
                    next=cur.next;
                    //pre的next值小于cur的值,pre指针后移。即找到cur应该插入的位置。
                    while(pre.next!=null && pre.next.val<cur.val){
                        pre=pre.next;
                    }
              //将cur插到pre与pre.next之间 cur.next
    =pre.next; pre.next=cur; cur=next; pre=newHead; } return newHead.next; }
  • 相关阅读:
    小网络的激活函数
    Dual Path Networks
    RT600之Mailbox
    RT600之OTFAD
    RSA算法详解
    RT600之SB
    RT600之master key
    RT600之PUF
    RT600 Boot详解
    RT如何生成image
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8478176.html
Copyright © 2011-2022 走看看