欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

链式队列的实现

程序员文章站 2022-07-14 13:50:44
...
#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct node{
	int data;
	struct node* next;
}Node;

typedef struct{
	Node *front;
	Node *rear;
}Queue;

//新建队列
void initQueue(Queue &Q){
	Q.front = Q.rear = new Node;
	Q.front -> next = NULL;
}

//队列判空
bool isEmptyQueue(Queue &Q){
	
	if(NULL == Q.front){    //此时队列被销毁
		exit(1);
	}
	if(Q.front == Q.rear)    
		return true;	//队列为空
		
	return false;
}

//入队
void enterQueue(Queue &Q, int element){
	Node *p = new Node;
	p -> next = NULL;
	p -> data = element;
	Q.rear -> next = p;
	Q.rear = p;
}

//出队
int deQueue(Queue &Q){
	int  outElement;
	if(isEmptyQueue(Q)){
		exit(1);
	}
	
	Node *p = Q.front -> next;
	outElement = p -> data;
	
	Q.front -> next = p -> next;
	if(Q.rear == p){
		Q.rear = Q.front;
	}
	delete p;
	
	return outElement;
}

//求队列长度
int getLength(Queue &Q){
	Node* p1 = Q.front;
	Node* p2 = Q.rear;
	int length = 0;
	
	while(p1 != p2){
		p1 = p1 -> next;
		length++;
	}

	return length;
}

//访问头部
int getHead(Queue & Q){
	if(isEmptyQueue(Q)){
		exit(1);
	}
	return Q.front -> next -> data;
}

//清空队列
void clearQueue(Queue &Q){
	while(!isEmptyQueue(Q)){
		deQueue(Q);
	}
}

//销毁队列
void destroyQueue(Queue &Q){
	clearQueue(Q);
	delete Q.front;
	Q.front = Q.rear = NULL;
}

int main(){
	Queue Q;
	initQueue(Q);
	cout << getLength(Q) << endl;

	for(int i = 1; i <= 10; ++i){
		enterQueue(Q, i);
	}
	cout << getHead(Q) << endl;
	cout << getLength(Q) << endl;

	while(!isEmptyQueue(Q)){
		cout << deQueue(Q) << " ";
	}
	cout << endl;

	if(!isEmptyQueue(Q))
		cout << "Yes" << endl;
	else
		cout << "NO" << endl;

	clearQueue(Q)
	
	if(!isEmptyQueue(Q))
		cout << "Yes" << endl;
	else
		cout << "NO" << endl;
		
	destroyQueue(Q);
	
	return 0;
}
相关标签: 数据结构