链式队列的实现

来源:互联网 发布:淘宝排行 编辑:程序博客网 时间:2024/05/16 16:09

 这今天,要做一个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

原创粉丝点击