队列C实现

来源:互联网 发布:淘宝助理创建宝贝 编辑:程序博客网 时间:2024/05/24 01:43

以下代码,均在VC上验证

 

#include<iostream.h>
#include<malloc.h>
//----------------单链队列,队列的链式存储结构------------------------
typedef struct QNode//声明一个单链队列数据类型
{
 int data;
 struct QNode *next;
}QNode,*QueuePtr;

typedef struct//声明队列数据类型
{
 QueuePtr front;//队列的头指针
 QueuePtr rear;//队列的尾指针
}LinkQueue;
//*******************************************************************

void CreateQueue(LinkQueue &Q)//创建一个队列
{
 Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));//存储分配
 if(!Q.front)
 {
  cout<<"error"<<endl;
 }
 else
 {
  Q.front->next=NULL;
 }
}

void InsertQueue(LinkQueue &Q,int e)//插入一个数据,即入队
{
 QueuePtr p=(QueuePtr)malloc(sizeof(QNode));
 p->data=e;
 p->next=NULL;
 Q.rear->next=p;//将插入的结点插入到队尾;由于头指针和为指针初始均指向头节点,所以此时,头指针仍指向头节点(注意是头节点不是队头节点)
 Q.rear=p;//队尾指针指向新插入的队尾节点
}

void DeleteQueue(LinkQueue &Q,int &e)//从队列Q中删除一个数据,由e返回该数据;即出队
{
  QueuePtr p;
 if(Q.front==Q.rear)
  cout<<"error"<<endl;
 else
 {
  p=Q.front->next;//队头元素地址赋给结点指针p
  e=p->data;
  Q.front->next=p->next;
  if(Q.rear==p)
   Q.rear=Q.front;
  free(p);//释放对头结点
 }
}

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

void PrintQueue(LinkQueue &Q)
{
 QueuePtr temp;
 if(Q.front)
 {
  if(Q.front->next==NULL)
  {
   cout<<"此队列为空"<<endl;
  }
  else
  {
   temp=Q.front;
   while(temp->next)
   {
    temp=temp->next;
    cout<<temp->data<<endl;
   }
  }
 }
 else
 {
  cout<<"此队列被销毁"<<endl;
 }
}
void main()//以下代码均是为了验证各个函数进行的操作
{
 LinkQueue Q;//定义一个队列
 int e;
 CreateQueue(Q);//创建队列Q
 PrintQueue(Q);//打印队列Q,以查看队列数据


 for(int i=0;i<10;i++)//入队操作
 {
  InsertQueue(Q,i);
 }
 PrintQueue(Q);

 

 cout<<"入队一个数据后"<<endl;
 InsertQueue(Q,12);//
 PrintQueue(Q);

 cout<<"出队一个数据后"<<endl;
 //DeleteQueue(Q,e);
 DeleteQueue(Q,e);//出队
 PrintQueue(Q);//打印此时队列Q数据
 cout<<"出队元素为:";
 cout<<e<<endl;

 DestroyQueue(Q);//销毁队列
 PrintQueue(Q);//打印,以验证是否销毁
}

 

原创粉丝点击