Possible Duplicate:
context switch during doubly linked list creation
I was reading The Design of the UNIX Operating System (Maurice Bach).
He gives the following example of a doubly linked-list.
struct queue{
//pointers (back and forward)
//other data
}*bp, *bp1
bp1->forp = bp->forp; //1
bp1->backp = bp; //makes sense
bp->forp = bp1; //makes sense
bp1->forp->backp = bp1; //2
I can’t understand the purpose of the statements marked 1 and 2. 1 seems wrong, 2 looks to be redundant.
Is this a valid way to create a doubly linked-list?
The code is correct.
bpis a doubly linked list.You want to insert
bp1intobpas the second item in the list (that is what the code does).To do that you need to set 4 pointers:
bp1->forpshould point to the second item in the list,bp->forp(//1above)bp1->backpshould point to the first item in the list,bpbp->forpshould point to the inserted item,bp1The back pointer of the second item,
bp1->forp->backpshould point to the inserted item,bp1. (//2above)Edit:
Let’s call the structs A, B, C, D…
The list (pointed to by
bpconsists of A, C, D… before the insert. We want to insert B (pointed to bybp1.<->denotes the forward and backwards pointers.Before:
After: