/*look at the use of structures and pointers to produce a double linked list that lists events in time order*/ #include #include #include int main (void) { int cont,time; typedef struct { int time; struct event *fptr,*bptr; } event; event *baseptr,*newptr,*tempptr,*tf,*tb; /* create the base element for the queue */ baseptr = (event *) malloc (sizeof (event)); /* set up the base of the queue to point to itself with time = 0 */ baseptr->time = 0; baseptr->fptr = baseptr; baseptr->bptr = baseptr; /*enter a loop to collect events */ time = 999; while (time > 0) { printf("Enter the time for the next event (t = 0 for quit) "); scanf("%i",&time); if (time == 0) printf("quiting\n"); else { /*create a new pointer */ newptr = (event *) malloc (sizeof (event)); newptr->time = time; newptr->bptr = newptr; /* initialise */ newptr->fptr = newptr; /* place the event into the double linked list in the correct place */ tempptr = baseptr; /*start off at the root */ cont = 1; do /* loop to work back until correct entry point found */ { tempptr = tempptr->bptr; if (newptr->time > tempptr->time) cont = 0; if (tempptr == baseptr) cont = 0; } while (cont == 1); /* rearrange the pointers to enter the new event */ newptr->fptr = tempptr->fptr; newptr->bptr = tempptr; tb = tempptr->fptr; tb->bptr = newptr; tempptr->fptr = newptr; } } /* end of entering new events */ /* now we will write the events out in order */ tempptr = baseptr->bptr; printf("Event pointer %p time = %i\n",tempptr,tempptr->time); while (tempptr != baseptr) { tempptr = tempptr->bptr; printf("Event pointer %p time = %i\n",tempptr,tempptr->time); } }