Using insertion sort on a singly linked list

前端 未结 7 1003
春和景丽
春和景丽 2021-02-06 10:11

So I have an assignment where I\'m giving a random list of number and I need to sort them using insertion sort. I must use a singly linked list. I looked around at other posts b

7条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 10:43

    void linked_list::insertion_sort() {
        node * p = head;
        node * currentNode = head->next; // The node that is being compared at the moment.
        node * previousNode = head; // The node previous to the node being compared at the moment.
        //We can return from the sorting if the length of the linked list is less than 2.
        if (p == nullptr || p->next == nullptr) {
            return;
        }
    
        while (currentNode != nullptr) {
    //If the current node is larger than or equal to the largest element of the sorted linked list on the left, we can move to the next element. 
    //Helpful for an already sorted array.
            if(previousNode->value<=currentNode->value){
                currentNode = currentNode->next;
                previousNode = previousNode->next;
            }
            else{
    //If the element is the smaller than the head element we need to take care of the head element.
                if (head->value > currentNode->value) {
                    previousNode->next = currentNode->next;
                    currentNode->next = head;
                    head = currentNode;
                }else {
                    p = head;
                    while (p->next != NULL && p->next->value < currentNode->value) {
                            p = p->next;
                    }
                    previousNode->next = currentNode->next;
                    currentNode->next = p->next;
                    p->next = currentNode;
                }
            }
            currentNode = previousNode->next;
        }
    }
    

提交回复
热议问题