# Include <stdio. h> # Include <stdlib. h> # Define max_size 50 Typedef struct qnode { Int data; // data domain Struct qnode * Next; // points to the next element } Qnode, * queueptr; Typedef struct { Queueptr front; // queue header pointer Queueptr rear; // The end pointer of the queue. Int length; // Queue Length } Linkqueue; // Construct an empty queue Void initqueue (linkqueue & Q) { Q. Front = Q. Rear = (queueptr) malloc (sizeof (qnode )); If (! Q. Front) { Exit (1 ); } Q. Front-> next = NULL; Q. Length = 0; Return; } // Destroy the queue Void destroyqueue (linkqueue & Q) { While (Q. Front) { Q. Rear = Q. Front-> next; If (Q. Front) { Free (Q. Front ); } Q. Front = Q. rear; } Q. Length = 0; } // Insert elements into the queue Void enqueue (linkqueue & Q, int e) { If (Q. Length = max_size) { Printf ("the queue is full! Element cannot be inserted! "); } Else { Queueptr P = (queueptr) malloc (sizeof (qnode )); If (! P) { Exit (1 ); } P-> DATA = E; P-> next = NULL;
Q. Rear-> next = P; // point to the newly inserted Node Q. Rear = P; Q. Length ++; // Add 1 to the number of elements } } // Output queue, from the queue Header Void dequeue (linkqueue * q, int e) { // The queue cannot be deleted because it is empty. If (Q-> front = Q-> rear) { Printf ("the queue is empty and cannot be deleted! "); } Else { Queueptr P = Q-> front-> next; // retrieve the queue Header E = p-> data; Q-> front-> next = p-> next; // delete node P Q-> length --; // The number of elements minus 1
// If the queue has only one element If (Q-> rear = P) { Q-> rear = Q-> front; } If (P! = NULL) { Free (P ); P = NULL; } } } // Calculate the queue length Int getlength (linkqueue * q) { Return Q-> length; } // Retrieve the queue Header element Int gethead (linkqueue * q) { If (0 = Q-> length) { Printf ("the queue is empty! \ N "); } Else { Return Q-> front-> next-> data; } } // Obtain the end element of the queue Int gettail (linkqueue * q) { If (0 = Q-> length) { Printf ("the queue is empty! \ N "); } Else { Return Q-> rear-> data; } } Void main () { Linkqueue Q; Initqueue (Q ); Enqueue (Q, 1 ); Enqueue (Q, 2 ); Enqueue (Q, 3 ); // Dequeue (& Q, 0 ); Int Len = getlength (& Q ); Printf ("the queue has several elements in total: % d, % d, % d \ n", Len, gethead (& Q), gettail (& Q )); Int daxiao = sizeof (qnode ); } |