简体   繁体   English

将元素插入已排序的循环双链表

[英]Insert element into a sorted Circular Double Linked List

i want to Insert an element into a sorted Circular Double Linked List ,, here's what i tried : 我想将元素插入到已排序的循环双链表中,这是我尝试的操作:

void insertSorted(Node *&head,int x){
    Node *temp = new Node();
    temp->data = x;
    temp->next = temp;
    temp->prev = temp;

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

    Node *p = head;
    Node *q = NULL;
    do{
        q = p;
        p=p->next;
    }while(p != head && x>p->data);

    if(q == NULL){
        temp->next = head;
        head->prev = temp;
        head = temp;
    }
    else {
        q->next = temp;
        if(p!=NULL){
            temp->next = p;
            p->prev = temp;
        }
        temp->prev = q;
    }
}

The Code works , but the problem is with the first element everytime it's not sorted ,,, example inserting 10 9 8 1 2 ,,, the output will be 10 1 2 8 9 ,, it should be 1 2 8 9 10 代码可以工作,但是问题是每次不排序时第一个元素都会出现问题,例如插入10 9 8 1 2,例如,输出将是10 1 2 8 9,应该是1 2 8 9 10

if(q == NULL) never gonna occur as per your code. if(q == NULL)永远不会按照您的代码发生。 So, the problem occurs here . 因此,这里出现问题。

As you are getting problem for the first node then , the condition should be (q == head) and update the head. 当第一个节点出现问题时,条件应为(q == head)并更新head。 that your code is doing correct. 您的代码执行正确。

void sortedInsert(int data){
    Nodo* ins = (Nodo*)malloc(sizeof(Nodo));
    ins->data = data;
    Nodo* itr = head;
    //case: empty
    if (head == NULL) {
        ins->next = ins;
        ins->prev = ins;
        head = ins;
        return;
    }
    //case: at begining
    else if (head->data > data){
        head->prev->next = ins;
        ins->prev = head->prev;
        ins->next = head;
        head->prev = ins;
        head = ins;
        return;
    }
    else {
        while (itr->data < data) {
            // case: at end of list
            if (itr->next == head) {
                ins->next = head;
                ins->prev = itr;
                itr->next = ins;
                head->prev = ins;
                return;
            }
            else {
                itr = itr->next;
            }
        }
        // case: middle
        itr->prev->next = ins;
        ins->prev = itr->prev;
        itr->prev = ins;
        ins->next = itr;
        return;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM