日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Insertion Sort List(单链表插入排序)

發(fā)布時(shí)間:2024/1/17 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Insertion Sort List(单链表插入排序) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

來(lái)源:https://leetcode.com/problems/insertion-sort-list

Sort a linked list using insertion sort.

?

方法:

1. 使用一個(gè)preHead指向頭節(jié)點(diǎn),這樣在將節(jié)點(diǎn)插入頭節(jié)點(diǎn)前面時(shí)(即某個(gè)節(jié)點(diǎn)值比頭節(jié)點(diǎn)小)不需要進(jìn)行特殊處理

2. 從頭節(jié)點(diǎn)開(kāi)始遍歷,如果當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)的值比當(dāng)前節(jié)點(diǎn)的值大,就從頭開(kāi)始遍歷找到第一個(gè)比當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)的值大的節(jié)點(diǎn),并插入到它的前面,注意插入時(shí)需要同時(shí)處理節(jié)點(diǎn)移出位置和插入位置的指針。

?

?直接插入排序:

時(shí)間復(fù)雜度,平均O(n^2),最好O(1),此時(shí)節(jié)點(diǎn)本身有序,最壞O(n^2)

空間復(fù)雜度,需要的輔助存儲(chǔ)為O(1)

穩(wěn)定性,穩(wěn)定,值相同的元素在排序后相對(duì)順序保持不變

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

?

轉(zhuǎn)載于:https://www.cnblogs.com/renzongxian/p/7554016.html

總結(jié)

以上是生活随笔為你收集整理的Insertion Sort List(单链表插入排序)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。