Insertion Sort List(单链表插入排序)
生活随笔
收集整理的這篇文章主要介紹了
Insertion Sort List(单链表插入排序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
來源:https://leetcode.com/problems/insertion-sort-list
Sort a linked list using insertion sort.
?
方法:
1. 使用一個preHead指向頭節點,這樣在將節點插入頭節點前面時(即某個節點值比頭節點小)不需要進行特殊處理
2. 從頭節點開始遍歷,如果當前節點的下一個節點的值比當前節點的值大,就從頭開始遍歷找到第一個比當前節點的下一個節點的值大的節點,并插入到它的前面,注意插入時需要同時處理節點移出位置和插入位置的指針。
?
?直接插入排序:
時間復雜度,平均O(n^2),最好O(1),此時節點本身有序,最壞O(n^2)
空間復雜度,需要的輔助存儲為O(1)
穩定性,穩定,值相同的元素在排序后相對順序保持不變
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode insertionSortList(ListNode head) { 11 ListNode preHead = new ListNode(0); 12 ListNode next = null, node = null, tmpNode = null; 13 preHead.next = head; 14 while(head != null) { 15 next = head.next; 16 if(next != null && next.val < head.val) { 17 node = preHead; 18 while(node.next != null && node.next.val <= next.val) { 19 node = node.next; 20 } 21 tmpNode = node.next; 22 node.next = next; 23 head.next = next.next; 24 next.next = tmpNode; 25 } else { 26 head = head.next; 27 } 28 } 29 return preHead.next; 30 } 31 }// 8 ms?
轉載于:https://www.cnblogs.com/renzongxian/p/7554016.html
總結
以上是生活随笔為你收集整理的Insertion Sort List(单链表插入排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 踩坑记(1)——使用slf4j+logb
- 下一篇: 如何在官网中下载历史版本的火狐浏览器