队列链式结构C/C++实现(数据结构严蔚敏版)

1、头文件Queue.h;

#include<iostream>
#include<iomanip>//格式控制头文件
#include<stdlib.h>
using namespace std;

//using namespace std;

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int Status;
typedef int QElemType;

typedef struct QNode{ //链队列结点的类型定义

   QElemType data;
   struct QNode *next;
   
}QNode,*QueuePtr;

typedef struct{ //链队列的表头结点的的类型定义

   QueuePtr front;//队头指针,指向链表头结点
   QueuePtr rear; //队尾指针,指向队尾结点
   
}LinkQueue;

Status InitQueue(LinkQueue &Q);

Status DestroyQueue(LinkQueue &Q);

Status EnQueue(LinkQueue &Q, QElemType e);

Status DeQueue(LinkQueue &Q, QElemType &e);

void PrintQueue(LinkQueue Q);


2、源文件Queue.cpp

#include "Queue.h" 
//初始化队列 
Status InitQueue(LinkQueue &Q){
	
	//构造一个空队列Q,建立一个头结点 
	Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
	
	if(!Q.front)  
		exit(OVERFLOW);
	
	//头节点的指针域为NULL 
	Q.front->next = NULL;
	return OK;
}


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


//插入队尾 
Status EnQueue(LinkQueue &Q, QElemType e){
	//插入元素e为Q的新队尾元素
	QueuePtr p = 
          (QueuePtr)malloc(sizeof(QNode));
	if(!p)
		exit(OVERFLOW);
	p->data = e;
	p->next = NULL;
	Q.rear->next = p;
	Q.rear = p;
	return OK;
}


//删除队列的头 
Status DeQueue(LinkQueue &Q, QElemType &e){
	//若队列不为空,则删除Q的队头元素,用e返回其值,
     //并返回OK;否则返回ERROR
	if(Q.front == Q.rear)
		return ERROR;
	QueuePtr p = Q.front->next;
	e = p->data;
	Q.front->next = p->next;
	
	
	if(Q.rear == p)     //唯一的数据结点出队,
                       //队尾指针空置       
		Q.rear = Q.front;
	free(p);
	return OK;
}


//打印队列 
void PrintQueue(LinkQueue Q){
	//显示队列
     if(Q.front == Q.rear)
		cout<<"队列为空\n";
		
     QueuePtr p = Q.front->next;
     
	 while(p!=NULL){
		 cout<<setw(6)<<p->data;
		 p=p->next;
	 }
}


3、测试文件test.cpp

#include "Queue.h" 
int main(void){

    LinkQueue Q;
	int i,n,e;
    cout<<"构造队列:\n";
	InitQueue(Q);
	cout<<"输入要构造队列的结点个数:";
	cin>>n;
	for (i=1;i<=n;i++)
	{
	   cout<<"输入第"<<i<<"个结点的值";
	   cin>>e;	
	   if(!EnQueue(Q,e)) break;
	};
	cout<<"构造的队列为:";
    PrintQueue(Q);
    cout<<endl;
  
	cout<<"入队一个新结点,值为:";
	cin>>e;
	if(EnQueue(Q,e)) 
	{
		cout<<"新队列为:\n";
		PrintQueue(Q);
		cout<<endl;
	}
	else
		cout<<"error!\n";


   cout<<"出队一个结点\n";
   if (DeQueue(Q,e))
   {
       cout<<"出队元素值为:"<<e<<endl;
	   cout<<"新队列为:\n";
       PrintQueue(Q);
	   cout<<endl;
   }

   else
	   cout<<"error!\n";
	   
	   
	DestroyQueue(Q);
}







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

圣诞节不感冒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值