链式队列的实现

 这今天,要做一个AIS解析的东西,需要用到队列数据结构,于是乎就自己写了一个测试了一下,现在给大家奉献出来!

 

代码在附件里面。

 

#include <stdio.h>
#include<stdlib.h>
#define MAX_SIZE 50
typedef struct QNode
{
 int data;    //数据域
 struct QNode *next;  //指向下一个元素
}QNode,*QueuePtr;

typedef struct
{
 QueuePtr front;   //队列头指针
 QueuePtr rear;   //队列尾指针
 int length;    //队列的长度
}LinkQueue;

//构造一个空队列
void InitQueue(LinkQueue &Q)
{
 Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
 if (!Q.front)
 {
  exit(1);
 }
 Q.front->next = NULL;
 Q.length = 0;
 return;
}

//销毁队列
void DestroyQueue(LinkQueue &Q)
{
 while (Q.front)
 {
  Q.rear = Q.front->next;
  if (Q.front)
  {
   free(Q.front);
  }
  Q.front = Q.rear;
 }
 Q.length = 0;
}

//插入元素,入队列
void EnQueue(LinkQueue &Q,int e)
{
 if (Q.length == MAX_SIZE)
 {
  printf("队列已经满了!不能插入元素!");
 }
 else
 {
  QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
  if (!p)
  {
   exit(1);
  }
  p->data = e;
  p->next = NULL;
  
  Q.rear->next = p; //指向新插入的节点
  Q.rear = p;    
     Q.length ++;  //元素个数加1
 } 
}

//出队列,从队列头出来
void DeQueue(LinkQueue *Q,int e)
{
 //队列是空的,不能删除
 if (Q->front == Q->rear)
 {
  printf("队列已经为空,不能删除!");
 }

 else
 {
  QueuePtr p = Q->front->next; //取出队列头
  e = p->data;
  Q->front->next = p->next;  //删除节点p
  Q->length --;     //元素个数减1
  
  //如果队列只有一个元素
  if (Q->rear == p)
  {
   Q->rear = Q->front;
  }
  if (p != NULL)
  {
   free(p);
   p = NULL;
  }
 }
}

//求队列长度
int GetLength(LinkQueue *Q)
{
 return Q->length;
}

//取队列的头元素
int GetHead(LinkQueue *Q)
{
 if (0 == Q->length)
 {
  printf("队列为空!\n");
 }
 else
 {
  return Q->front->next->data;
 }
}

//取队列的尾元素
int GetTail(LinkQueue *Q)
{
 if (0 == Q->length)
 {
  printf("队列为空!\n");
 }
 else
 {
  return Q->rear->data;
 }
}
void main()

 LinkQueue Q;
 InitQueue(Q);
 EnQueue(Q,1);
 EnQueue(Q,2);
 EnQueue(Q,3);
 //DeQueue(&Q,0);

 int len = GetLength(&Q);
 printf("队列总共有几个元素:%d,%d,%d\n",len,GetHead(&Q),GetTail(&Q));
 int daxiao = sizeof(QNode);
}

 

 

 

程序的运行结果如下:

队列总共有几个元素:3,1,3
Press any key to continue

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值