您的位置:首页 > 其它

链式队列基本操作总结

2011-03-18 10:55 375 查看
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef struct _QNODE
{
int data;
struct _QNODE *next;
}Qnode;

typedef struct _QUEUE
{
Qnode *front;
Qnode *rear;
}LinkQueue;

#define SIZE_OF_NODE sizeof(struct _QNODE)
#define SIZE_OF_QUEUE sizeof(struct _QUEUE)

void Init_LinkQueue(LinkQueue **QL);
LinkQueue *Insert_Queue(LinkQueue *QL, int key);
LinkQueue *Delete_Queue(LinkQueue *QL);
int Length_LinkQueue(LinkQueue *QL);
void Print_Queue(LinkQueue *QL);

int main()
{
LinkQueue *QL = NULL;
int array[] = {3,1,2,5,7,6,9};
int i = 0, len, length;

len = sizeof(array) / sizeof(int);
Init_LinkQueue(&QL);

for(i = 0; i < len; ++i)
{
QL = Insert_Queue(QL, array[i]);
}
printf("The LinkQueue you created is :/n");
Print_Queue(QL);
length = Length_LinkQueue(QL);
printf("/nThe length of the queue is : %d/n", length);
QL = Delete_Queue(QL);
QL = Delete_Queue(QL);
printf("/nAfter two times delete the queue is :/n");
Print_Queue(QL);
puts("");
return 0;
}

void Init_LinkQueue(LinkQueue **QL)
{
(*QL) = (LinkQueue *)malloc(SIZE_OF_QUEUE);
if((*QL) == NULL)
{
printf("Memeory assign error!!/n");
exit(1);
}
(*QL)->front = (*QL)->rear = NULL;
}

LinkQueue *Insert_Queue(LinkQueue *QL, int key)
{
Qnode *s = NULL;

s = (Qnode *)malloc(SIZE_OF_NODE);
if(s == NULL)
{
printf("Memrory assign error!!/n");
exit(1);
}
else
{
s->data = key;
s->next = NULL;
if(QL->rear == NULL) //queue is empty
{
QL->front = s;
QL->rear = s;
}
else
{
QL->rear->next = s;
QL->rear = s;
}
}
return QL;
}

LinkQueue *Delete_Queue(LinkQueue *QL)
{
Qnode *node;
int key;

if(QL->front == NULL)
{
printf("Overflow of the linkqueue!!/n");
exit(1);
}
else
{
key = QL->front->data ;
node = QL->front ;
if(QL->front == QL->rear )
{
QL->front = NULL;
QL->rear = NULL;
}
else
{
QL->front = QL->front->next;
free(node);
node = NULL;
}
}
return QL;
}

int Length_LinkQueue(LinkQueue *QL)
{
int len = 0;
Qnode *node;

node = QL->front ;
while(node != NULL)
{
node = node->next;
len++;
}
return len;
}

void Print_Queue(LinkQueue *QL)
{
Qnode *node = NULL;

node = QL->front;
while(node != NULL)
{
printf("/n %d-> ", node->data );
node = node->next;
}
}
/*
The LinkQueue you created is :

3->
1->
2->
5->
7->
6->
9->
The length of the queue is : 7

After two times delete the queue is :

2->
5->
7->
6->
9->
Press any key to continue
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: