队列是先进先出(FIFO),栈是先进后出(FILO),用线性链表来实现队列,思路和实现链栈类似,可以参阅: 链栈的C实现 下面是代码: #include <stdio.h> #include <stdlib.h> typedef struct __Node{ int data; struct __Node *pre; struct __Node *next; }Node; typedef struct __queue{ Node *head; Node *tail; }queue; void init(queue *Q){ if(Q== NULL){ printf("Fail to initialize the queue! It doesn't exist/n"); return; } Q->head = NULL; Q->tail = NULL; } int isEmpty(queue Q){ if(Q.head == NULL) return 1; else return 0; } void add(queue *Q, int data){ Node *p = NULL; if(Q == NULL){ printf("Fail to add new element! The queue doesn't exist/n"); return; } if(isEmpty(*Q) == 1){ p = (Node*)malloc(sizeof(Node)); if(p == NULL){ printf("Fail to allocate memory!/n"); return; } p->data = data; p->pre = NULL; p->next = NULL; Q->head = p; Q->tail = p; } else{ p = (Node*)malloc(sizeof(Node)); if(p == NULL){ printf("Fail to allocate memory!/n"); return; } p->data = data; p->next = NULL; p->pre = Q->tail; Q->tail->next = p; Q->tail = p; } } int remove(queue *Q){ Node *p = NULL; int result = 0; if(Q == NULL){ printf("Fail to add new element! The queue doesn't exist!/n"); return NULL; } if(isEmpty(*Q) == 1){ printf("Fail to add new element! The queue is empty!/n"); return NULL; } else if(Q->head == Q->tail){ p = Q->head; result = p->data; free(p); p = NULL; Q->head = NULL; Q->tail = NULL; return result; } else{ p = Q->head; result = p->data; p->next->pre = NULL; Q->head = p->next; free(p); p = NULL; return result; } } int peek(queue Q){ if(Q.head == NULL){ return -1; } else return Q.head->data; } void traversal(queue Q){ Node *p = NULL; p = Q.head; printf("开始遍历.../n/n"); while(p != NULL){ printf("%d ", p->data); p = p->next; } printf("遍历结束/n/n"); } void destroy(queue *Q){ Node *p = NULL; Node *temp = NULL; if(isEmpty(*Q) == 1){ printf("Fail to destroy the queue! The queue doesn't exist!/n"); return NULL; } p = Q->head; while(p != NULL){ temp = p; p = p->next; free(temp); temp = NULL; } Q->head = NULL; Q->tail = NULL; } int main(int argc, char **args){ queue Q; int i = 0; int pk = 0; memset(&Q, 0, sizeof(queue)); init(&Q); traversal(Q); remove(&Q); for(i=0;i<20;++i){ add(&Q, i); } traversal(Q); remove(&Q); remove(&Q); traversal(Q); add(&Q, 100); add(&Q, 99); add(&Q, 98); traversal(Q); remove(&Q); remove(&Q); remove(&Q); remove(&Q); traversal(Q); pk = peek(Q); printf("对列头元素是 %d/n/n", pk); destroy(&Q); traversal(Q); remove(&Q); return 0; }