数据结构实现——链队列
原创不易,转载请声明出处。
刚学队列,若有BUG,欢迎反馈
使用的函数功能介绍
Queue *Creat()
功能:创建空队列,返回Queue*,作为该队列的指针。
特殊情况:当无法申请空间时,返回NULL。
使用方法:
Queue *Q = Creat();
int Destroy(Queue* Q)
功能:删除队列,若成功,返回1;
特殊情况:当队列已经被删除(Q为空指针),返回0。
注意:使用之后,一定要立即将指针置空
int Push(Queue *Q, Elem e)
功能:向队列中添加一个元素;
特殊情况:若失败,返回0。
int Pop(Queue *Q)
功能:将队首元素出列。
特殊情况:若失败,返回0.
int Empty(Queue *Q)
功能:判断队列是否为空。为空返回1,非空返回0
特殊情况:若失败,返回-1。
Elem GetHead(Queue *Q)
Elem GetTail(Queue *Q)
功能:获取队首以及队尾元素。
特殊情况:若失败,让程序Crash
int Size(Queue *Q)
功能:返回队列内的元素个数。
若失败,返回-1。
源代码
#include <stdio.h>
#include <stdlib.h>
typedef int Elem;
typedef struct Node
{
Elem data;
struct Node *next;
}Node;
typedef struct Queue
{
Node *head,*tail;
int cnt;
}Queue;
Queue *Creat()
{
Queue* Q = (Queue*)malloc(sizeof(Queue));
if(Q == NULL)
return NULL;
Q->head = NULL;
Q->tail = NULL;
Q->cnt = 0;
return Q;
}
int Destroy(Queue* Q)
{
if(Q == NULL)
return 0;//已经被删除
if(Q->head != NULL)
{
Node *p = Q->head;
while(p)
{
Node* q = p;
p = p->next;
free(q);
}
}
free(Q);
Q = NULL;
return 1;
}
int Push(Queue *Q, Elem e)
{
if(!Q)
return 0;
Node *s = (Node*)malloc(sizeof(Node));
if(!s)
return 0;
s->data = e;
s->next = NULL;
if(Q->head)
{
Q->tail->next = s;
Q->tail = s;
}
else
{
Q->head = Q->tail = s;
}
Q->cnt++;
return 1;
}
int Pop(Queue *Q)
{
if(!Q)
return 0;
if(Q->head==NULL)
return 0;
Node *p = Q->head;
Q->head = p->next;
free(p);
Q->cnt--;
return 1;
}
int Empty(Queue *Q)
{
if(!Q)
return -1;
if(Q->head == NULL)
return 1;
else
return 0;
}
Elem GetHead(Queue *Q)
{
return Q->head->data;
}
Elem GetTail(Queue *Q)
{
if(Q->head == NULL)
*(int *)0;
return Q->tail->data;
}
int Size(Queue *Q)
{
if(!Q)
return -1;
return Q->cnt;
}
int main()
{
Queue *Q = Creat();
printf("size:%d\n",Size(Q));
printf("empty?:%d\n",Empty(Q));
Push(Q,1);
printf("empty?:%d\n",Empty(Q));
Push(Q,2);
printf("%d %d\n",GetHead(Q),GetTail(Q));
printf("size:%d\n",Size(Q));
Pop(Q);
Pop(Q);
printf("fault_signal:%d\n",Pop(Q));
Push(Q,2);
printf("Size:%d\n",Size(Q));
Destroy(Q);
Q = NULL;
printf("fault_signal:%d\n",(Push(Q,1)));
return 0;
}
总结:增强程序的健壮性
- 对传入的指针判空。
- 对在程序中执行逻辑的合理新判断(判断链表是不是空之类的)
3.对于申请空间,判断一下是否成功(传承其他函数的错误提示)
更多推荐:
数据结构实现——循环队列