一、链队相关
链队不用考虑队满的情况,每次在队尾添加新元素。
二
链队列的类型描述:
1
2
3
4
5
6
7
8
9
10
|
//链队列类型描述
typedef
int
QElemType;
typedef struct node{
QElemType data;
struct node *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
//队头指针
QueuePtr rear;
//队尾指针
}LinkQueue;
|
基本操作:
1. 链队列的初始化(带头结点)Init_LinkQueue(LinkQueue *Q)
1
2
3
4
5
6
7
8
|
//链队列的初始化(带头结点)
void
Init_LinkQueue(LinkQueue *Q){
QueuePtr head = (QueuePtr)malloc(sizeof(QNode));
if
(!head)
exit(OVERFLOW);
head->next = NULL;
Q->front = Q->rear = head;
}
|
2. 销毁链队列Destroy_LinkQueue(LinkQueue *Q)
1
2
3
4
5
6
7
8
9
|
//销毁链队列
void
Destroy_LinkQueue(LinkQueue *Q){
//从头结点开始释放链队列中所有的结点
while
(Q->front){
Q->rear = Q->front->next;
free(Q->front);
Q->front = Q->rear;
}
}
|
3. 清空链队列Clear_LinkQueue(LinkQueue *Q)
1
2
3
4
5
|
//清空链队列
void
Clear_LinkQueue(LinkQueue *Q){
Destroy_LinkQueue(Q);
Init_LinkQueue(Q);
}
|
4. 判断链队列是否为空IsEmpty_LinkQueue(LinkQueue *Q)
1
2
3
4
5
|
//判断链队列是否为空
int
IsEmpty_LinkQueue(LinkQueue *Q){
return
Q->front == Q->rear;
}
|
5. 求链队列的长度GetLength_LinkQueue(LinkQueue *Q)
1
2
3
4
5
6
7
8
9
10
11
|
//求链队列的长度
int
GetLength_LinkQueue(LinkQueue *Q){
int
count =
0
;
//指向存放数据的第一个结点
QueuePtr p = Q->front->next;
while
(p){
count++;
p = p->next;
}
return
count;
}
|
6. 取得链队列的头部元素GetHead_LinkQueue(LinkQueue *Q,QElemType *x)
1
2
3
4
5
6
7
8
9
10
|
//取得链队列的头部元素
void
GetHead_LinkQueue(LinkQueue *Q,QElemType *x){
if
(IsEmpty_LinkQueue(Q)){
printf(
"链队列为空!\n"
);
exit(
0
);
}
else
{
*x = Q->front->next->data;
}
}
|
7. 取得链队尾的头部元素GetRear_LinkQueue(LinkQueue *Q,QElemType *x)
1
2
3
4
5
6
7
8
9
10
|
//取得链队尾的头部元素
void
GetRear_LinkQueue(LinkQueue *Q,QElemType *x){
if
(IsEmpty_LinkQueue(Q)){
printf(
"链队列为空!\n"
);
exit(
0
);
}
else
{
*x = Q->rear->data;
}
}
|
8. 入链队列En_LinkQueue(LinkQueue *Q,QElemType x)
1
2
3
4
5
6
7
8
9
10
|
//入链队列
void
En_LinkQueue(LinkQueue *Q,QElemType x){
QueuePtr q = (QueuePtr)malloc(sizeof(QNode));
if
(!q)
exit(OVERFLOW);
q->data = x;
q->next = NULL;
Q->rear->next = q;
Q->rear = q;
}
|
9. 出链队列De_LinkQueue(LinkQueue *Q,QElemType *x)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//出链队列
void
De_LinkQueue(LinkQueue *Q,QElemType *x){
QueuePtr q;
if
(IsEmpty_LinkQueue(Q)){
printf(
"链队列为空!\n"
);
exit(
0
);
}
else
{
*x = Q->front->next->data;
q = Q->front->next;
*x = q->data;
Q->front->next = q->next;
//删除元素后队列为空
if
(q->next == NULL)
Q->rear = Q->front;
free(q);
}
}
|
10. 输出链队列Print_LinkQueue(LinkQueue *Q)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//输出链队列
void
Print_LinkQueue(LinkQueue *Q){
//p指向头结点的下一个结点,即存放数据的第一个结点
QueuePtr p = Q->front->next;
if
(IsEmpty_LinkQueue(Q)){
printf(
"链队列为空!\n"
);
exit(
0
);
}
else
{
while
(p){
printf(
"%d\t"
,p->data);
p = p->next;
}
printf(
"\n"
);
}
}
|