顺序队列(进队出队)

#include <stdio.h>
#include "stdlib.h"

int enQueue(int *a,int rear,int data){		//入队  数组a  队尾   数据 
    a[rear]=data;							//a[0]=元素 
    rear++;									//每入一次队尾+1 
    return rear;							//返回队尾 
}	
void deQueue(int *a,int front,int rear){	//出队 
    //如果 front==rear,表示队列为空
    while (front!=rear) {					
        printf("出队元素:%d\n",a[front]);	//a[0]  先进先出 
        front++;							//队头+1  依次打印出队 
    }
}
int main() {
    int a[100];								//定义个够大的数组	 
    int front,rear;							//定义队头队尾 
    //设置队头指针和队尾指针,当队列中没有元素时,队头和队尾指向同一块地址
    front=rear=0;
    //入队
    rear=enQueue(a, rear, 1);
    rear=enQueue(a, rear, 2);
    rear=enQueue(a, rear, 3);
    rear=enQueue(a, rear, 4);
    //出队
    deQueue(a, front, rear);
    return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,以下是使用C语言实现顺序队列的代码,包括数据进队出队和遍历队列操作: ```C #include <stdio.h> #define MAXSIZE 100 // 定义队列的最大容量 // 定义顺序队列结构体 typedef struct { int data[MAXSIZE]; // 队列数据存储数组 int front; // 队列头指针 int rear; // 队列尾指针 } SeqQueue; // 初始化队列 void initQueue(SeqQueue *queue) { queue->front = queue->rear = 0; } // 判断队列是否为空 int isEmpty(SeqQueue *queue) { return queue->front == queue->rear; } // 判断队列是否已满 int isFull(SeqQueue *queue) { return queue->rear == MAXSIZE; } // 入队操作 void enQueue(SeqQueue *queue, int value) { if (isFull(queue)) { printf("队列已满,无法入队!\n"); return; } queue->data[queue->rear++] = value; } // 出队操作 int deQueue(SeqQueue *queue) { if (isEmpty(queue)) { printf("队列已空,无法出队!\n"); return -1; } int value = queue->data[queue->front]; queue->front++; return value; } // 遍历队列 void traverseQueue(SeqQueue *queue) { if (isEmpty(queue)) { printf("队列为空,无法遍历!\n"); return; } printf("队列中的元素为:"); for (int i = queue->front; i < queue->rear; i++) { printf("%d ", queue->data[i]); } printf("\n"); } int main() { SeqQueue queue; initQueue(&queue); printf("顺序队列初始化成功!\n"); enQueue(&queue, 1); enQueue(&queue, 2); enQueue(&queue, 3); printf("入队操作完成!\n"); traverseQueue(&queue); printf("队头元素出队:%d\n", deQueue(&queue)); printf("出队操作完成!\n"); traverseQueue(&queue); return 0; } ``` 顺序队列使用数组来存储队列中的元素,使用front指针来指向队头元素,使用rear指针来指向队尾元素的下一个位置。当队列为空时,front和rear都指向数组的第一个元素。当队列已满时,rear指针指向数组的最后一个元素。在入队操作时,将元素放入rear指针所指向的位置,并将rear指针后移一位。在出队操作时,将front指针所指向的元素出队,并将front指针后移一位。遍历队列时,从front指针所指向的位置开始遍历,直到rear指针所指向的位置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wiyoo0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值