[LeetCode] C++: Intermediate Question-Linked List 147. Insert and Sort Linked List

147. Insert Sort on Linked List

Medium difficulty 344

Insert sort on the linked list.


The animation demonstration of insertion sort is as above. Starting from the first element, the linked list can be considered partially sorted (indicated in black).
At each iteration, an element (indicated in red) is removed from the input data and inserted in-situ into the sorted linked list.

 

Insertion sort algorithm:

  1. Insertion sort is iterative, moving only one element at a time until all elements can form an ordered output list.
  2. In each iteration, insertion sort only removes an element to be sorted from the input data, finds its proper position in the sequence, and inserts it.
  3. Repeat until all input data is inserted.

 

Example 1:

输入: 4->2->1->3
输出: 1->2->3->4

Example 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

----------------------Update-------------------------

Finally, after I understand it, come over and write an analysis

Focus on the later analysis part!

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(head == nullptr){
            return head;
        }
        ListNode* dummyHead = new ListNode();
        dummyHead->next = head;
        ListNode* lastSorted = head;
        ListNode* curr = head->next;
        while(curr != nullptr){
            if(lastSorted->val <= curr->val){
                lastSorted = lastSorted->next;
            }else{
                ListNode* prev = dummyHead;
                while(prev->next->val <= curr->val){
                    prev = prev->next;
                }
                lastSorted->next = curr->next;
                curr->next = prev->next;
                prev->next = curr;
            }
            curr = lastSorted->next;
        }
        return dummyHead->next;
    }
};

Because it is a singly linked list, the linked list has only one backward pointer, so when dealing with changing positions, you need to find the previous node prev that needs to change nodes from the beginning. The reason prev = dummyHead is a dumb node, because in the loop prev->next->val <= curr->val is used to compare prev->next, so that the head comparison will not be lost, while the exchange In the position, prev->next should be the node in the correct order. This place must be drawn.

Take 6->5->3 as an example, the default sorting is from small to large, dummy is a dummy node, dummy->next is a head node, and the initial lastSort is a head node. This is easy to understand because you can imagine that there is only one node at the beginning Sorted well. curr is head->next, that is, curr points to the next node of the last sorted node, then judge the value of the last sorted node and the size of the current node value at this time, if the current node value is greater than the last sorted node The node value of, so just loop directly to the next one. If the current node value is less than the value of the last sorted node, the current value needs to be inserted before the sorted node. But I don’t know where to insert it, so I start looping from the beginning node to find a node larger than the current value. In the while loop, prev starts from the dummy node, and compares the prev->next value with the current value each time. The advantage of this is to It is convenient to exchange and sort after finding the exchange position. If prev is initially set to head, then the previous node to be inserted into the node will not be found, and there will be no pointer. This is not possible in a singly linked list.

lastSort->next = curr->next, this line of code transfers the next node of the current value to the next node in the sort order. It can be understood that the current value is to be inserted before the sort, so this next node should be Give the next node of the last node after the previous sorting, (do the handover work, hee hee).

curr->next = prev->next insert the current value into the position of the sort, (find home).

prev->next = curr Give curr the penultimate node of the sorted sequence, and then curr can go to the next loop

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113618477