# 佇列的陣列實現

## 1. 在佇列中插入元素的演算法

``````第1步：IF REAR = MAX - 1
寫OVERFLOW
轉到第4步
[IF結束]

SET FRONT = REAR = 0
其他
SET REAR = REAR + 1
[IF結束]

``````

``````void insert (int queue[], int max, int front, int rear, int item)
{
if (rear + 1 == max)
{
printf("overflow");
}
else
{
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear + 1;
}
queue[rear]=item;
}
}
``````

## 2. 從佇列中刪除元素的演算法

``````第1步：IF FRONT = -1或FRONT> REAR
提示溢位
其他
SET VAL = QUEUE [FRONT]
SET FRONT = FRONT + 1
[IF結束]

``````

C語言實現演算法，如下所示 -

``````int delete (int queue[], int max, int front, int rear)
{
int y;
if (front == -1 || front > rear)

{
printf("underflow");
}
else
{
y = queue[front];
if(front == rear)
{
front = rear = -1;
else
front = front + 1;

}
return y;
}
}
``````

``````#include<stdio.h>
#include<stdlib.h>
#define maxsize 5
void insert();
void delete();
void display();
int front = -1, rear = -1;
int queue[maxsize];
void main()
{
int choice;
while (choice != 4)
{
printf("=================================================================\n");
printf("1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("Enter valid choice??\n");
}
}
}
void insert()
{
int item;
printf("\nEnter the element\n");
scanf("\n%d", &item);
if (rear == maxsize - 1)
{
printf("OVERFLOW\n");
return;
}
if (front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear + 1;
}
queue[rear] = item;
printf("Value inserted ");

}
void delete()
{
int item;
if (front == -1 || front > rear)
{
printf("UNDERFLOW\n");
return;

}
else
{
item = queue[front];
if (front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
printf("value deleted ");
}

}

void display()
{
int i;
if (rear == -1)
{
printf("Empty queue\n");
}
else
{
printf("printing values .....\n");
for (i = front;i <= rear;i++)
{
printf("\n%d\n", queue[i]);
}
}
}
``````

``````*************Main Menu**************

==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter the element
123

Value inserted

==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter the element
90

Value inserted

===================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

value deleted

==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

printing values .....

90

==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

上圖顯示了如何在佇列的陣列表示中浪費記憶體空間。 在上圖中，示出了具有`3`個元素的大小為`10`的佇列。 `front`變數的值為`5`，因此，不能將值重新插入`front`位置之前已刪除元素的位置。 陣列的那麼多空間被浪費了，以後不能使用(對於這個佇列)。