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

时间:2015-07-11 23:46:32

标签: c++ c data-structures

我想将一个元素插入一个已排序的循环双链表,这是我试过的:

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;
    }
}

代码有效,但问题是第一个元素每次没有排序,,,例如插入10 9 8 1 2 ,,,输出将是10 1 2 8 9 ,,它应该是1 2 8 9 10

2 个答案:

答案 0 :(得分:0)

根据您的代码,

if(q == NULL)永远不会发生。所以,这里出现问题。

当您遇到第一个节点的问题时,条件应为(q == head)并更新头部。您的代码正确无误。

答案 1 :(得分:0)

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;
    }
}