简体   繁体   中英

Doubly linked list, add node in-order

I want to keep my doubly linked list sorted all the time and keep the head and the tail node pointers updated. I managed to keep the head pointer updated in all operations but I can not keep track of the tail pointer. It only shows the last element as tail->info but can not go back as doing tail=tail->prev; here is my code:

AddInOrder(node* &head, node* &tail, int number) {     

    node *ptr=head; 

    if (head==NULL || number<head->info) {       

        node*temp=new node;

        temp->info=number; 
        temp->next=head;   
        temp->prev=NULL;
        head=temp;   
        tail=temp;    
        return 0;
    }

    while(ptr->next!=NULL && ptr->next->info<number) {         
        ptr=ptr->next;                                        
    }

    node*temp=new node;              
    temp->info=number;
    temp->next=ptr->next;
    temp->prev=ptr;
    ptr->next=temp;

    while(ptr->next!=NULL) {
        ptr=ptr->next;                 
    }

    tail=ptr;             

    return 0;
}          

@JonathanPotter was right. "You're not setting ptr->prev when you link a new node in." that is the problem. this code works fine for me. see the modification, added some part for setting prev node. code may be little messy but you may understand the logic and write a better code.

int AddInOrder(node* &head, node* &tail, int number) 
{     
    node *ptr=head; 
    node*temp=new node;
    temp->info=number; 

    if ( head==NULL )
    {
        temp->next=head;   
        temp->prev=NULL;
        head=temp;
        tail = temp;

        return 0;
    }

    if ( number<head->info )
    { 
        temp->next=head;   
        temp->prev=NULL;

        head->prev = temp;
        head=temp;
        return 0;
    }

    while(ptr->next!=NULL && ptr->next->info<number) 
    {         
        ptr=ptr->next;    
        continue;
    }

    if (ptr->next != NULL)
    {
        ptr->next->prev = temp;
    }
    temp->next=ptr->next;
    temp->prev=ptr;
    ptr->next=temp;

    while(ptr->next!=NULL)
    {
            ptr=ptr->next;                 
    }

    tail=ptr;             

    return 0;
}       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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