Leetcode-insertion-sort-list ***

来源:互联网 发布:多媒体互动教学软件 编辑:程序博客网 时间:2024/06/06 10:38

题目描述


Sort a linked list using insertion sort.


题目越短,事情越大。


用插入排序法对链表进行排序。


我是参考别人的解答做的,这题我不会。


 * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode insertionSortList(ListNode head) {       if(head == null || head.next == null)    return head;        ListNode cursors = head;    ListNode tempCur = null;    ListNode temp = head;  //待排序元素的上一个 元素    ListNode current = temp.next; //待排序元素        while(current != null){    if(current.val < head.val){    temp.next = current.next; //待排序元素上一个元素指向待排序元素下一个元素    current.next = head;    head = current;    }else{                //     cursors-↓    ↓-temp                //   1 -> 3 -> 5 -> 8 -> 4-> 12 -> 2                //tempCur-↑      current-↑                //插入后:                //  |-------有序---------|                //  1 -> 3 -> 4 -> 5 -> 8-> 12 -> 2                //找到插入的位置 current插入到cursors的前面:temp->current->cursors    tempCur = cursors;    cursors = tempCur.next;    while(cursors != current && cursors.val < current.val){    tempCur = cursors;    cursors = cursors.next;    }    if(cursors == current){    temp = current;    current = temp.next;    }else{    temp.next = current.next;    tempCur.next = current;    current.next = cursors;    }    }    cursors = head;    current = temp.next;    }    return head;     }}

数组的插入排序是从待排序元素往前找插入位置,而链表则是从头开始找插入位置。

0 0