c語言隊列實現(xiàn)代碼 C語言隊列實現(xiàn)代碼詳解
隊列是一種常見的數(shù)據(jù)結構,它遵循先進先出(First In First Out,F(xiàn)IFO)的原則。在C語言中,可以通過數(shù)組或鏈表來實現(xiàn)隊列。下面我們將分別介紹這兩種實現(xiàn)方式。1. 數(shù)組實現(xiàn)隊列數(shù)組實現(xiàn)
隊列是一種常見的數(shù)據(jù)結構,它遵循先進先出(First In First Out,F(xiàn)IFO)的原則。在C語言中,可以通過數(shù)組或鏈表來實現(xiàn)隊列。下面我們將分別介紹這兩種實現(xiàn)方式。
1. 數(shù)組實現(xiàn)隊列
數(shù)組實現(xiàn)隊列的基本思想是使用一個固定大小的數(shù)組來存儲數(shù)據(jù)元素,并使用兩個指針front和rear分別指向隊頭和隊尾。初始化時,front和rear都指向數(shù)組的第一個元素。入隊操作時,將元素插入rear指向的位置,并將rear后移一位;出隊操作時,將front指向的元素移除,并將front后移一位。需要注意的是,當rear指向數(shù)組末尾時,再有元素入隊時需要進行循環(huán)處理。
下面是使用數(shù)組實現(xiàn)隊列的示例代碼:
```c
#include
#define SIZE 100
int queue[SIZE];
int front -1;
int rear -1;
int isEmpty()
{
if (front -1 || front > rear)
return 1;
else
return 0;
}
int isFull()
{
if (rear SIZE - 1)
return 1;
else
return 0;
}
void enqueue(int data)
{
if (isFull())
printf("Queue is full.
");
else
{
if (front -1)
front 0;
rear ;
queue[rear] data;
}
}
int dequeue()
{
if (isEmpty())
{
printf("Queue is empty.
");
return -1;
}
else
{
int data queue[front];
front ;
return data;
}
}
int main()
{
enqueue(1);
enqueue(2);
enqueue(3);
printf("%d
", dequeue());
printf("%d
", dequeue());
printf("%d
", dequeue());
return 0;
}
```
2. 鏈表實現(xiàn)隊列
鏈表實現(xiàn)隊列的基本思想是使用一個單向鏈表來存儲數(shù)據(jù)元素,并使用兩個指針front和rear分別指向隊頭和隊尾。初始化時,front和rear都指向NULL。入隊操作時,將新節(jié)點插入rear指向節(jié)點的后面,并將rear指向新節(jié)點;出隊操作時,將front指向的節(jié)點移除,并將front后移一位。需要注意的是,當鏈表為空時,front和rear都應該指向NULL。
下面是使用鏈表實現(xiàn)隊列的示例代碼:
```c
#include
#include
struct Node
{
int data;
struct Node* next;
};
struct Node* front NULL;
struct Node* rear NULL;
int isEmpty()
{
if (front NULL)
return 1;
else
return 0;
}
void enqueue(int data)
{
struct Node* newNode (struct Node*) malloc(sizeof(struct Node));
newNode->data data;
newNode->next NULL;
if (isEmpty())
{
front newNode;
rear newNode;
}
else
{
rear->next newNode;
rear newNode;
}
}
int dequeue()
{
if (isEmpty())
{
printf("Queue is empty.
");
return -1;
}
else
{
struct Node* temp front;
int data temp->data;
front front->next;
free(temp);
return data;
}
}
int main()
{
enqueue(1);
enqueue(2);
enqueue(3);
printf("%d
", dequeue());
printf("%d
", dequeue());
printf("%d
", dequeue());
return 0;
}
```
以上是C語言中隊列的兩種常見實現(xiàn)方式:數(shù)組和鏈表。通過對代碼的詳細解析,我們可以更好地理解隊列的原理和操作過程,從而能夠靈活運用隊列解決實際問題。希望本文能對讀者有所幫助。