您的位置:首页 > 其它

Leetcode-insertion-sort-list ***

2016-07-17 17:18 405 查看


题目描述

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;
}
}


数组的插入排序是从待排序元素往前找插入位置,而链表则是从头开始找插入位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: