您的位置:首页 > 其它

链队列基本函数

2017-11-30 15:29 162 查看
头文件:

#ifndef LINKQUEUE_H_
#define LINKQUEUE_H_

#define SUCCESS 10000
#define FAILURE 10001

typedef int ElemType;

typedef struct node
{
ElemType data;
struct node *next;
}Node;

typedef struct queue
{
Node *front;
Node *rear;
}Queue;

#endif


子函数:

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

int InitQueue(Queue *L)
{
L->front =(Node *)malloc(sizeof(Node));
if(NULL == L->front)
{
return FAILURE;
}
L->front->next = NULL;
L->rear = L->front;
return SUCCESS;
}

int EnQueue(Queue *L,ElemType e,int count)
{
Node *n = (Node *)malloc (sizeof(Node));

n->next = NULL;
n->data = e;
L->rear->next = n;
L->rear = n;

return SUCCESS;

}

int QueueLength(Queue L)
{
Node *n = L.front;
int count = 0;
while(n->next != NULL)
{
count++;
n = n->next;

}

return count;
}

int GetTop(Queue L)
{
while(NULL != L.front->next)
{
return L.front->next->data;
}
}

int DeleteQueue(Queue *L)
{
ElemType e;
Node *p = L->front->next;
if(NULL == p)
{
return FAILURE;
}
L->front->next = p->next;
e = p->data;
free(p);

if(L->front->next == NULL)
{
L->rear = L->front;
}

return e;

}

int ClearQueue(Queue *L)
{
Node *p = L->front->next;
if(NULL == p)
{
return FAILURE;
}
while(NULL != p)
{
L->front->next = p->next;
free(p);
p = L->front->next;

if(L->front->next == NULL)
{
L->rear = L->front;
}
}

}

int DestroyQueue(Queue *L)
{
free(L->front);
L->front = NULL;
L->rear = NULL;

return SUCCESS;
}


主函数:

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

int main()
{
int ret,i;
ElemType e;
Queue sq;

ret = InitQueue(&sq);
if(FAILURE == ret)
{
printf("Init Failure!\n");
}
else
{
printf("Init Success!\n");
}

for(i = 0; i < 8; i++)
{
e = i + 1;
ret = EnQueue(&sq,e);
if(FAILURE == ret)
{
printf("Enter %d Failure!\n",e);
}
else
{
printf("Enter %d Success!\n",e);
}
}

printf("Length is %d\n",QueueLength(sq));

printf("The top is %d\n",GetTop(sq));

for(i = 0; i < 7; i++)
{
ret = DeleteQueue(&sq);
if(FAILURE == ret)
{
printf("Delete Failure!\n");
}
else
{
printf("Delete %d Success!\n",ret);
}
}

ret = ClearQueue(&sq);
if(FAILURE == ret)
{
printf("Clear Failure!\n");
}
else
{
printf("Clear Success!\n");
}

ret = DestroyQueue(&sq);
if(FAILURE == ret)
{
printf("Destroy Failure!\n");
}
else
{
printf("Destroy Success!\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  队列 链队列