ordered doubly linked list

this code insert elements in doubly linked list in ascending order but when i try to insert element in between or bigger than those exist the program stops working


int DLL :: InsertOrd(EleType x){
node *p,*q;

p=new node;
p->data=x;
if(L==NULL){
return Construct(x);
}
else if (L->next==NULL){
if(L->data < x ){
return InsertRear(x);
}
else{
return InsertFront(x);
}

}

else{
q=L;
if(x< q->data) {

return InsertFront(x);
}
else{
while(q!=NULL && x > q->data){
q=q->next;
}
node *K;
if(x > q->data){
q=L;
K->next=p;
p->next=q;
p->prv=K;
q->prv=p;

}
} PrintList();
}

return 1;

}
Last edited on
Put your code inside [code]code tags[/code] to make it easier to read. I'm not sure what L is, or if your InsertFront and InsertRear functions work correctly, but there's a problem here:

1
2
3
4
node *K;
if(x > q->data){
q=L;
K->next=p;

You have not set K to point at anything, but you're trying to access K->next.
L referes to the first node in the list .k is a pointer points to the node before q.
I don't think that you're understanding what I'm saying.

node *K;

You created a pointer to a node, and called it K.

K->next=p;

You try to access the next member of the node pointed to by K.

The problem is that you didn't say what node K points to. So how are you supposed to access its next member?

Here is a (poor) analogy:

A variable is a box.
A node variable is a box that can only hold nodes.
A node * (node pointer) variable is a box that can only hold the location of a node box.
You created a node pointer box.
You did not put the location of a node box inside the node pointer box.
The operator -> tells the program to reach into the node pointer box, retrieve the location of the node box, go to the node box, and reach in to retrieve the next from the node box.
But this is impossible because the node pointer box does not contain the location of any node box.
Last edited on
Topic archived. No new replies allowed.