目录
-
队列的基础知识
- 队列遵循先进先出,即FIFO(first in first out)。例如:我们经常见到的排队买票、排队买饭等等;
- 队列的两个基本操作:
入队 :将一个数据放到队列尾部;
出队 :从队列的头部取出一个元素。
-
初始化一个队列节点
inline qu* Init_Queue(qu* q, int data) //初始化一个队列节点
{
q->data = data;
q->next = NULL;
return q;
}
-
入队
qu* Insert_Queue(qu* q, int data, int q_length)
{
qu* head = q;
qu* cut = q;
int i = 0;
if (q_length <= 0 || NULL == q) //参数合法性判断
{
cout << "Error queue length or queue is't init." << endl;
return NULL;
}
for (i = 0; i < q_length; i++) //依次插入数据
{
qu* newq = (qu*)malloc(sizeof(qu));
if (head->next == NULL) //只有一个头节点
{
head->next = newq;
cut = newq;
Init_Queue(newq, data + i);
}
else //已经又出头节点之外其他节点
{
cut->next = newq;
Init_Queue(newq, data + i);
cut = newq;
}
}
return q;
}
-
出队
void Out_Queue(qu* q, int q_length)
{
int i = 0;
if (NULL == q)
return;
qu* head = q;
cout << "出队:"<<endl;
cout << endl;
q = head->next; //跳过头节点
for(i = 1; i< q_length +1; ++i)
{
if (q->next != NULL)
{
cout << q->data << " ";
}
else
cout << q->data << " ";
q = q->next;
}
}
-
链表队列的实现代码
#include <iostream>
#include <string>
using namespace std;
typedef struct queue
{
int data;
struct queue* next;
}qu;
inline qu* Init_Queue(qu* q, int data); //初始化一个队列的节点
qu* Insert_Queue(qu* q, int data, int q_length); //入队
void Out_Queue(qu* q, int q_length); //出队
int main()
{
qu* q1;
q1 = (qu *)malloc(sizeof(qu));
qu* q2 = Insert_Queue(Init_Queue(q1, -1), 96, 21);
Out_Queue(q2, 21);
return 0;
}
inline qu* Init_Queue(qu* q, int data)
{
q->data = data;
q->next = NULL;
return q;
}
qu* Insert_Queue(qu* q, int data, int q_length)
{
qu* head = q;
qu* cut = q;
int i = 0;
if (q_length <= 0 || NULL == q)
{
cout << "Error queue length or queue is't init." << endl;
return NULL;
}
cout << "入队:" << endl;
for (i = 0; i < q_length; i++)
{
qu* newq = (qu*)malloc(sizeof(qu));
if (head->next == NULL)
{
head->next = newq;
cut = newq;
Init_Queue(newq, data + i);
cout << newq->data << " ";
}
else
{
cut->next = newq;
Init_Queue(newq, data + i);
cout << newq->data << " ";
cut = newq;
}
}
return q;
}
void Out_Queue(qu* q, int q_length)
{
int i = 0;
if (NULL == q)
return;
qu* head = q;
cout << "出队:"<<endl;
q = head->next; //跳过头节点
for(i = 1; i< q_length +1; ++i)
{
if (q->next != NULL)
{
cout << q->data << " ";
}
else
cout << q->data << " ";
q = q->next;
}
}
-
程序运行结果