leetcode并查集,Leetcode Insertion Sort List

 2023-12-06 阅读 36 评论 0

摘要:Sort a linked list using insertion sort. 鏈表的插入排序,其實有2種特殊情況: 1、插入的值插入到已排序的末尾。 leetcode并查集,2、插入的值插入到已排序的最前端。 主要設置了3個指針。 1、pStart是已排序鏈表的開始位置。 2、pInsert是待插入的位置。 LE

Sort a linked list using insertion sort.

鏈表的插入排序,其實有2種特殊情況:

1、插入的值插入到已排序的末尾。

leetcode并查集,2、插入的值插入到已排序的最前端。

主要設置了3個指針。

1、pStart是已排序鏈表的開始位置。

2、pInsert是待插入的位置。

LEETCODE。3、pEnd是下一個等待排序的位置。

key:每個已排序的鏈表最后的Node的next指針為null。這樣可以防止循環鏈表,已得不到正確值。


public class Solution {
???? public ListNode insertionSortList(ListNode head) {
??????? if(head == null||head.next == null)return head;
??????? ListNode pStart = head;
??????? ListNode pInsert = head.next;
??????? pStart.next = null;
??????? ListNode pEnd = head;
??????? while(pInsert != null)
??????? {
??????????? pEnd = pInsert.next;
??????????? pStart = sort(pStart,pInsert);
??????????? pInsert = pEnd;
??????? }
??????? head = pStart;
??????? return head;
??? }
???
??? public ListNode sort(ListNode head,ListNode insert)
??? {
??????? ListNode start = head;
??????? ListNode pStr = head;
??????? if(head == null)return head;
??????? while(start.val < insert.val && start.next != null)
??????? {
??????????? pStr = start;
??????????? start = start.next;
??????? }
??????? if(start.val >= insert.val && start == head)
??????? {
??????????? insert.next = head;
??????????? head = insert;
??????? }
??????? else if(start.val >= insert.val)
??????? {
??????????? pStr.next = insert;
??????????? insert.next = start;
??????? }
??????? else if(start.next == null)
??????? {
??????????? start.next = insert;
??????????? insert.next = null;
??????? }
??????? return head;
??? }
}

轉載于:https://www.cnblogs.com/jessiading/p/3715982.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/192758.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息