- 论坛徽章:
- 0
|
1可用积分
- #include <stdio.h>
- #include <stdlib.h>
- #define MAXNUM 40
- #define datatype int
- typedef struct queue{
- int queue[MAXNUM];
- int front;
- int rear;
- }queue;
- void initqueue(queue** p)
- {
- *p = (queue* )malloc(sizeof(queue));
- if(*p != NULL){
- (*p)->front = -1;
- (*p)->rear = -1;
- }
- }
- void enqueue(queue** p, datatype x)//将x插入队尾
- {
- if(((*p)->rear+1)%MAXNUM == (*p)->front){
- printf("the queue is full\n");
- }
- (*p)->rear = ((*p)->rear+1)%MAXNUM;
- (*p)->queue[(*p)->rear] = x;
- }
- void delqueue(queue** p, datatype* x)//删除队列头元素,用x返回
- {
- if((*p)->front == (*p)->rear){
- printf("the queue is empty\n");
- }
- (*p)->front = ((*p)->front+1)%MAXNUM;
- *x = (*p)->queue[(*p)->front];
- }
- void firstqueue(queue** p, datatype* x)//返回队列头元素
- {
- *x = (*p)->queue[(*p)->front];
- }
- void prqueue(queue** p)//打印队列元素
- {
- int i;
- for(i = (*p)->front; i <= (*p)->rear; i++){
- printf("%c", (*p)->queue[i]);
- }
- printf("\n");
- }
- int main(int argc, char** argv)
- {
- queue* p;
- int c;
- initqueue(&p);
- while((c = getchar()) !='\n'){
- enqueue(&p, c);
- }
- prqueue(&p);
- delqueue(&p, &c);//删除一个头元素
- printf("c = %c\n", c);
- printf("\n");
- enqueue(&p, 111);
- prqueue(&p);
- exit(0);
- }
复制代码
上面是简单的一个关于队列操作的实现
执行:
./a.out
1 2 3 4 5 6 //输入初始队列元素值
|
最佳答案
查看完整内容
你的队列是这样设计的,头指针指向第一个元素之前,尾指针指向最后一个元素。你的输出函数是这样的,输出头指针指向的元素,头指针指向的元素的后一个元素,...,直到最后一个元素。所以多了一个。在这个问题之外,你的输出函数仍有问题,因为 rear 可以比 front 小,你的 for 循环可能会在队列不空的情况下不输出。ps: 分就不要给我了,一分太少,拿了不好意思。
|