Inserting a Node Into a Sorted Doubly Linked List

  • + 0 comments

    in C:

    DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* llist, int data) {
        DoublyLinkedListNode** cur = &llist;
        DoublyLinkedListNode * new_node = calloc(sizeof(DoublyLinkedListNode), 1);
        new_node->data = data;
        
        while(*cur && ((*cur)->data < data)) {
            cur = &(*cur)->next;
        }
        
        new_node->next = (*cur);
        if(*cur) {
            new_node->prev = (*cur)->prev;
        }
        (*cur) = new_node;
        return llist;
    }