LeetCode 147-insert sort on linked list

1. Topic introduction

Insert sort on the linked list.

Insertion sort algorithm:

(1) Insertion sorting 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.

Two, problem-solving ideas

        Because the linked list structure given by the title is a singly linked list, there is no way to traverse from back to forward when inserting. Therefore, when the value of the current node is detected to be greater than the previous node, it is traversed from front to back to find the first one that is less than the current node. Node, and then insert. The following relationships need to be handled during the insertion process:

(1) The previous node preNode of the current node pNode points to the next node, that is, preNode->next = pNode->next.

(2) The current node points to the inserted node pTemp, that is, pNode->next = pTemp.

(3) Under the premise that the previous node p of the inserted node is not empty, point to the current node, p->next = pNode;

(4) If the inserted node is the head node, after the insertion is complete, the head node needs to be updated.

Three, problem-solving code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(head == NULL)
            return head;
        ListNode* pNode = head;
        ListNode* preNode = NULL;
        while(pNode)
        {
            if(preNode && pNode->val < preNode->val)
            {
                ListNode* pTemp = head;
                ListNode* p = NULL;
                while(pTemp != pNode)
                {
                    if(pTemp->val > pNode->val)
                    {
                        preNode->next = pNode->next; //前一个节点指向后一个节点
                        pNode->next = pTemp;//移动的节点指向被插入的节点
                        if(p)//被插入节点的前一个节点指向插入的节点
                            p->next = pNode;
                        if(pTemp == head) //更新头结点
                            head = pNode;
                        pNode = preNode;
                        break;
                    }
                    p = pTemp;
                    pTemp = pTemp->next;
                }
            }
            preNode = pNode;
            pNode = pNode->next;
        }
        return head;
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/109844117