30 Day Challenge Day 6 | Hackerrank: Inserting a Node Into a Sorted Doubly Linked List

题解

很简单的题,要注意检查空节点。

DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data) {
    if(!head) {
        head = new DoublyLinkedListNode(data);
        return head;
    }

    DoublyLinkedListNode* prev = nullptr;
    DoublyLinkedListNode* curr = head;
    while(curr && curr->data < data) {
        prev = curr;
        curr = curr->next;
    }

    DoublyLinkedListNode* node = new DoublyLinkedListNode(data);

    if(prev == nullptr) {
        node->next = head;
        return node;
    } else {
        prev->next = node;
        node->next = curr;
        return head;
    }
}
原文地址:https://www.cnblogs.com/casperwin/p/13636745.html