Loading

【leetcode】147. Insertion Sort List

Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.

The steps of the insertion sort algorithm:

  1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
  3. It repeats until no input elements remain.

The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.

Example 1:

Input: head = [4,2,1,3]
Output: [1,2,3,4]
  

    本题考查的是链表的插入排序,因为不是双向链表,需要两个快慢指针维护前后遍历的两个节点。

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        // 对链表进行插入排序
        // 时间复杂度的话就是o(n2)了
        // 插入第一个大于当前元素的前面
        if(head->next==nullptr) return head;
        ListNode* node=new ListNode(0);
        node->next=head;
      
        ListNode* cur_fast=head->next;//需要排序的元素
        ListNode* cur_low=head; 
        
        while(cur_fast!=nullptr){
            
            ListNode *low=node;
            ListNode *fast=node->next;// 遍历插入位置的快慢指针
            
            while(fast!=cur_fast){
                if(fast->val>cur_fast->val){
                    break;
                }
                low=fast;
                fast=fast->next;
            }
            
            if(fast!=cur_fast){
                // 节点插入的话 需要交换节点 注意cur_fast 的前一个节点也需要处理 负责回出现死循环
                cur_low->next=cur_fast->next;
                low->next=cur_fast;
                cur_fast->next=fast;
                cur_fast=cur_low->next;
            }
            else{
                // 节点不插入的话 就继续遍历
                cur_low=cur_fast;
                cur_fast=cur_fast->next; 
            }
        }
        return node->next;
    }
};
posted @ 2021-12-15 16:57  aalanwyr  阅读(42)  评论(0)    收藏  举报