您的位置:首页 > 其它

队列的链表实现

2015-09-23 11:20 323 查看
queue.h:

#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
struct Node;
typedef struct Node QNode;
struct Queue;
typedef struct Queue *PtrQ;

PtrQ CreateQueue();
void MakeEmpty(PtrQ Q);
int DeQueue(PtrQ Q);
void EnQueue(int X, PtrQ Q);

#endif // QUEUE_H_INCLUDED


实现文件

implementation.c:

#include<stdio.h>
#include "queue.h"

typedef struct Node{
int Data;
struct Node *Next;
}QNode;

typedef struct Queue{
QNode *Rear;
QNode *Front;
}*PtrQ;

PtrQ CreateQueue(){
PtrQ Q;
Q = malloc(sizeof(struct Queue));
MakeEmpty(Q);
return Q;
}

void MakeEmpty(PtrQ Q) {
Q->Rear = Q->Front = NULL;
}

int DeQueue(PtrQ Q) {
QNode *FirstCell;
int FirstElem;
if(Q->Front == NULL){
printf("Error, EmptyQueue!");
return -1;
}
FirstCell = Q->Front;
if(Q->Rear == Q->Front) {
Q->Rear = Q->Front = NULL;
} else {
Q->Front = Q->Front->Next;
}
FirstElem = FirstCell->Data;
free(FirstCell);
return FirstElem;
}

void EnQueue(int X, PtrQ Q) {
QNode *TmpCell;
TmpCell = malloc(sizeof(struct Node));
TmpCell->Next = NULL;
TmpCell->Data = X;
if(Q->Front == NULL) {
Q->Rear = TmpCell;
Q->Front = TmpCell;
} else if(Q->Front == Q->Rear) {
Q->Rear = TmpCell;
Q->Front->Next = Q->Rear;
} else{
Q->Rear->Next = TmpCell;
Q->Rear = TmpCell;
}
}


测试文件:

main.c:

#include <stdio.h>
#include <stdlib.h>
#include "queue.h"

int main()
{
PtrQ Q;
int a, b, c;
Q = CreateQueue();
EnQueue(1, Q);
EnQueue(2, Q);
a = DeQueue(Q);
b = DeQueue(Q);
printf("%d ", a);
EnQueue(3, Q);
c = DeQueue(Q);
printf("%d ", b);
printf("%d", c);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: