C语言实现顺序队列
#include <stdio.h> #define NUMBER 100 int push_queue(int* a, int rear, int data) { a[rear] = data; rear++; return rear; } void pop_queue(int* a, int front, int rear) { while (front != rear) { printf("%d ",a[front]); front++; } printf("\n"); return; } int main() { int a[NUMBER]; int front, rear; front = 0; rear = 0; rear = push_queue(a, rear, 1); rear = push_queue(a, rear, 3); rear = push_queue(a, rear, 5); pop_queue(a, front, rear); return 0; }
第二种方法:解决上面那种浪费空间与可能出现溢出的情况
#include <stdio.h> #define NUMBER 5 int push_queue(int* a, int front, int rear, int data) { if ((rear + 1) % NUMBER == front) { printf("Space Full\n"); return rear; } a[rear % NUMBER] = data; rear++; return rear; } int pop_queue(int* a, int front, int rear) { if (front == (rear % NUMBER)) { printf("Space Empty\n"); return front; } printf("%d ",a[front]); front = (front + 1) % NUMBER; return front; } int main() { int a[NUMBER]; int front, rear; front = 0; rear = 0; rear = push_queue(a, front, rear, 1); rear = push_queue(a, front, rear, 3); rear = push_queue(a, front, rear, 5); rear = push_queue(a, front, rear, 6); front = pop_queue(a, front, rear); rear = push_queue(a, front, rear, 7); front = pop_queue(a, front, rear); rear = push_queue(a, front, rear, 9); front = pop_queue(a, front, rear); front = pop_queue(a, front, rear); front = pop_queue(a, front, rear); front = pop_queue(a, front, rear); return 0; }