int dequeue(){
if (isEmpty() == 1){
printf("The queue is empty.\n");
return 0;
}
else{
queue *output = front;
front = front->next; // the older data
free(output);
return output->Data; // return the top node
}
return -1;
}
2. Enqueue(): 將資料放入佇列的尾端。
void enqueue(int data){
// request space for new node
queue *new_node = (queue *)malloc(sizeof(queue));
// save the data to the new node
new_node->Data = data;
new_node->next = NULL;
// push to the back of the queue
if (isEmpty() == 1){
front = new_node;
rear = front;
}
else{
rear->next = new_node; // next of the rear node points to new node
rear = new_node;
}
}
3. 輸出結果範例:
Enqueue: 1, 2, 3
Queue: 1, 2, 3
Enqueue: 4, 5
Queue: 1, 2, 3, 4, 5
Dequeue, the front is: 1
Dequeue, the front is: 2
Queue: 3, 4, 5
int dequeue(){
queue *t = (queue *)malloc(sizeof(queue)); //暫時的變數
if (rear == NULL){
printf("The queue is empty.\n");
return 0;
}
else{
if (rear->next == rear){ //代表佇列中只有一筆資料
t = rear;
rear = NULL;
return t->Data;
}
else{
t = rear->next; //t為front
rear->next = t->next; //目前的front會被輸出,rear指向當前的front的下一筆資料成為新的front
return t->Data;
}
}
return -1;
}
2. Enqueue(): 將資料放入佇列的尾端。
void enqueue(int data){
// request space for new node
queue *new_node = (queue *)malloc(sizeof(queue));
// save the data to the new node
new_node->Data = data;
if (rear == NULL){ //Queue原本為空
new_node->next = new_node;
}
else{
new_node->next = rear->next; //new_node為最後一筆資料,需指向front
rear->next = new_node; //將new_node加入linklist
}
rear = new_node; //新的rear
}
3. 輸出結果範例:
Enqueue: 1, 2, 3
Queue: 1, 2, 3
Enqueue: 4, 5
Queue: 1, 2, 3, 4, 5
Dequeue, the front is: 1
Dequeue, the front is: 2
Queue: 3, 4, 5
Create a queue which size is 5.
Enqueue: 1, 2, 3
Queue: 1 2 3
Enqueue: 4
Queue: 1 2 3 4
Enqueue: 5
The queue is full.
Dequeue, the front is: 1
Dequeue, the front is: 2
Queue: 3 4
int dequeue(queue *qu){
if (qu->front == qu->rear && qu->tag == 0){
printf("The queue is empty.\n");
return 0;
}
else{
qu->front = (qu->front + 1) % qu->MAX_SIZE;
if (qu->front == qu->rear) qu->tag = 0; //檢查取出資料後佇列是否為空
return qu->Data[qu->front];
}
return -1;
}
3. Enqueue(): 將資料放到佇列的後端。
void enqueue(queue *qu, int data){
if (qu->front == qu->rear && qu->tag == 1){
printf("The queue is full.\n");
}
else{
qu->rear = (qu->rear + 1) % qu->MAX_SIZE;
qu->Data[qu->rear] = data;
if (qu->front == qu->rear) qu->tag = 1; //檢查輸入資料後佇列是否是滿的狀態
}
}
4. 輸出結果範例:
Create a queue which size is 5.
Enqueue: 1, 2, 3
Queue: 1 2 3
Enqueue: 4
Queue: 1 2 3 4
Enqueue: 5
The queue is full.
Dequeue, the front is: 1
Dequeue, the front is: 2
Queue: 3 4