mardi 3 mars 2015

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



Aucun commentaire:

Enregistrer un commentaire