C語言中佇列的插入元素是什麼?
資料結構是按結構化方式組織的資料集合。它分為如下兩種型別:
-
線性資料結構 − 資料以線性方式組織。例如,陣列、結構體、棧、佇列、連結串列。
-
非線性資料結構 − 資料以分層方式組織。例如,樹、圖、集合、表。
另請閱讀:資料結構和型別
佇列
佇列是一種線性資料結構,其中插入在隊尾進行,刪除在隊首進行。

佇列的順序是FIFO – 先進先出
操作
- 插入 – 將元素插入佇列。
- 刪除 – 從佇列中刪除元素。
條件
-
佇列溢位 − 嘗試將元素插入已滿的佇列。
-
佇列下溢 − 嘗試從空佇列中刪除元素。
演算法
以下是插入()演算法:
- 檢查佇列溢位。
if (r==n)
printf ("Queue overflow")
- 否則,將元素插入佇列。
q[r] = item r++
C程式用於插入佇列元素
以下是用於插入佇列元素的C程式:
#include <stdio.h>
#define MAX 50
void insert();
int array[MAX];
int rear = -1;
int front = -1;
main() {
int add_item;
int choice;
while (1) {
printf("1.Insert element to queue
");
printf("2.Display elements of queue
");
printf("3.Quit
");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
insert();
break;
case 2:
display();
break;
case 3:
exit(1);
default:
printf("Wrong choice
");
}
}
}
void insert() {
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow
");
else {
if (front == -1) /*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
array[rear] = add_item;
}
}
void display() {
int i;
if (front == -1)
printf("Queue is empty
");
else {
printf("Queue is :
");
for (i = front; i <= rear; i++) printf("%d ", array[i]);
printf("
");
}
}
輸出
執行上述程式後,將產生以下結果:
1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 1 Inset the element in queue: 34 1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 1 Inset the element in queue: 24 1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 2 Queue is: 34 24 1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 3
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP