您的位置:首页 > 理论基础 > 数据结构算法

数据结构---队列的链式实现

2015-04-16 15:08 417 查看
其实理解了一个数据结构后,它的各种实现与操作就能很容易的写出来 话说貌似下周数据结构有期中考试...Orz我翘了两次课 串和数组那地方还不太懂 要跪啊....

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

typedef int ElemType;

typedef struct Node
{
ElemType Data;
struct Node *Next;
}Node, *PtrNode;

typedef struct Queue
{
PtrNode Front;
PtrNode Rear;
}Queue, *LinkQueue;

//create an empty linkqueue
LinkQueue InitQueue();

//destroy linkqueue
void DestroyQueue(LinkQueue Q);

//clear a linkqueue
void ClearQueue(LinkQueue Q);

//if the linkqueue is empty return 1
int IsEmpty(LinkQueue Q);

//get the length of linkqueue
int QueueLength(LinkQueue Q);

//get the head of linkqueue
ElemType GetHead(LinkQueue Q);

//insert an element to the rear of linkqueue
void EnQueue(LinkQueue Q, ElemType E);

//get and delete the front of linkqueue
ElemType DeQueue(LinkQueue Q);

void PrintQueue(LinkQueue Q);

int main()
{
LinkQueue Q = InitQueue();
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
PrintQueue(Q);
printf("%d\n", GetHead(Q));
printf("%d\n", QueueLength(Q));
DeQueue(Q);
DeQueue(Q);
PrintQueue(Q);
DestroyQueue(Q);
return 0;
}

LinkQueue InitQueue()
{
LinkQueue Q = (LinkQueue)malloc(sizeof(Queue));
Q->Front = Q->Rear = (PtrNode)malloc(sizeof(Node));
Q->Front->Next = NULL;
return Q;
}

void DestroyQueue(LinkQueue Q)
{
while(Q->Front)
{
Q->Rear = Q->Front->Next;
free(Q->Front);
Q->Front = Q->Rear;
}
}

void ClearQueue(LinkQueue Q)
{
Q->Rear = Q->Front;
PtrNode Tmp = Q->Front->Next;
while(Tmp)
{
Q->Front = Tmp->Next;
free(Tmp);
Tmp = Q->Front;
}
Q->Front = Q->Rear;
}

int IsEmpty(LinkQueue Q)
{
return (Q->Front == Q->Rear) ? 1 : 0;
}

int QueueLength(LinkQueue Q)
{
int count = 0;
PtrNode Tmp = Q->Front;
while(Tmp != Q->Rear)
{
Tmp = Tmp->Next;
count ++;
}
return count;
}

ElemType GetHead(LinkQueue Q)
{
return Q->Front->Next->Data;
}

void EnQueue(LinkQueue Q, ElemType E)
{
PtrNode Tmp = (PtrNode)malloc(sizeof(Node));
Tmp->Data = E;
Tmp->Next;
Q->Rear->Next = Tmp;
Q->Rear = Tmp;
}

ElemType DeQueue(LinkQueue Q)
{
PtrNode Tmp = Q->Front->Next;
ElemType Data = Tmp->Data;
Q->Front->Next = Tmp->Next;
free(Tmp);
return Data;
}

void PrintQueue(LinkQueue Q)
{
PtrNode Tmp = Q->Front->Next;
while(Tmp)
{
printf("%d ", Tmp->Data);
Tmp = Tmp->Next;
}
printf("\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: