按顺序将节点插入排序的双链表中

时间:2018-08-16 19:14:18

标签: c++ insert nodes

我有用于将节点插入到链表中的代码。要求是代码从输入中消除重复项,并按顺序排列它们。它通过了多个测试用例,但不是全部。如果有人有任何见解,那将非常有帮助。谢谢。

DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data){

    DoublyLinkedListNode* temp = new DoublyLinkedListNode(data);

    if (head == NULL)  
    {   
        return temp;   
    }

    if (head->data == data)  
    {  
        return head;  
    }

    if (head->data > data)   
    {   
         temp->next = head;          
         return temp;   
    }

    if(head->next != NULL)  
    {    
         head->next = sortedInsert(head->next, data);   
    }

    else  
    {       
        head->next = temp;  
    }

    return head;

}

2 个答案:

答案 0 :(得分:1)

您的函数可以写为:

DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data)
{
    if( head and head->data <= data ) {
        if( head->data < data ) 
           head->next = sortedInsert(head->next, data);
        return head;
    }
    DoublyLinkedListNode* temp = new DoublyLinkedListNode(data);
    temp->next = head;
    return temp;
}

它更短,更简单并且没有内存泄漏。顺便说一句,将单个链表节点称为DoublyLinkedListNode通常不是一个好主意,也不是将原始指针返回到动态分配的内存,而是使用智能指针。

答案 1 :(得分:0)

DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data) {
    DoublyLinkedListNode* temp=head;
    DoublyLinkedListNode* newNode=(DoublyLinkedListNode*)malloc(sizeof(DoublyLinkedListNode));
    newNode->data=data;
    newNode->next=NULL;
    newNode->prev=NULL;
    if(head==NULL)                  //If head is empty
    {
        head=newNode;
        return head;
    }
    while(temp->data<data && temp->next!=NULL)     //Point to the node that is greater than data
    {
        temp=temp->next;
    }
    if(temp->prev==NULL)             //If the node to be inserted is first-Testcase1
    {
        newNode->next=temp;
        temp->prev=newNode;
        head=newNode;
    }
    else if(temp->next==NULL && temp->data<data)     //If the node to be inserted is last Test Case-2
    {

        newNode->prev=temp;    
        temp->next=newNode;
    }
    else                          //If the node to be inserted is middle Test Case-3
        {
            newNode->next=temp;
        newNode->prev=temp->prev;
        temp->prev->next=newNode;
        temp->prev=newNode;
        }
         return head;
}