zoukankan      html  css  js  c++  java
  • LeetCode题解-147 对链表进行插入排序

    对链表进行插入排序。
    gif
    插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
    每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。

    插入排序算法:

    插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
    每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
    重复直到所有输入数据插入完为止。

    示例 1:

    输入: 4->2->1->3
    输出: 1->2->3->4
    示例 2:

    输入: -1->5->3->4->0
    输出: -1->0->3->4->5

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode insertionSortList(ListNode head) {
           if(head==null)
               return null;
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            ListNode cur, suffix,pos=null;
            int move = 0;
            pos=head;
        while( pos != null){
    
            suffix = pos.next;
            cur = dummyHead;
           while( cur != suffix &&cur!=null&& cur.next.val < pos.val){
                cur = cur.next;
            }
            ListNode tpos = pos;
            pos.next = cur.next;
            cur.next = pos;
            while(pos.next!=null && pos.next != tpos){
                pos = pos.next ;
            }
            pos.next = suffix;
            pos = suffix;
            move++;
        }
            return dummyHead.next;
        }
    }
    
    内容来自博客园,拒绝爬虫网站
  • 相关阅读:
    几种任务调度的 Java 实现方法与比较
    nginx配置
    生产消费_lock和阻塞队列
    阻塞队列
    countdownlatch+cyclicbarrier+semphore
    01背包
    skiplist
    lru
    按序打印_lock和condition
    按序打印_volatile 无法保证顺序
  • 原文地址:https://www.cnblogs.com/Heliner/p/10793429.html
Copyright © 2011-2022 走看看