队列的C、C++实现

  • C
#include <stdio.h>
#include <stdlib.h>
struct Queue{
	int *data;
	int capacity;
	int front;
	int rear;
}; 

void init(struct Queue *pq,int capacity){
	pq->capacity=capacity;
	pq->data=(int*)malloc(sizeof(int)*(capacity+1));
	pq->front=pq->rear=0; 
}

int isFull(const struct Queue *pq){
	if((pq->rear +1)%(pq->capacity+1)==pq->front)	return 1;
	else return 0;
}

int isEmpty(const struct Queue *pq){
	return pq->front==pq->rear;
}

int enQueue(struct Queue *pq,int k){
	if(isFull(pq)) return 0;
	else{
		pq->data[pq->rear]=k;
		pq->rear=(pq->rear+1)%(pq->capacity+1);
		return 1;
	}
}

int deQueue(struct Queue *pq,int *px){
	if(isEmpty(pq))	return 0;
	else{
		*px=pq->data[pq->front];
		pq->front=(pq->front+1)%(pq->capacity+1);
		return 1;
	}
}

int main(){
	struct Queue q;
	init(&q,5);
	enQueue(&q,11);
	enQueue(&q,22);
	enQueue(&q,33);
	enQueue(&q,44);
	enQueue(&q,55);
	enQueue(&q,66);
	int x;
	deQueue(&q,&x);
	printf("%d\n",x);
	deQueue(&q,&x);
	printf("%d\n",x);
	deQueue(&q,&x);
	printf("%d\n",x);
	deQueue(&q,&x);
	printf("%d\n",x);
	deQueue(&q,&x);
	printf("%d\n",x);
	deQueue(&q,&x);
	printf("%d\n",x);
	return 0;
}
  • C++
#include <iostream> 
using namespace std;

struct Node{
	int data;
	Node *next;
	Node(int x){
		data=x;
		next=NULL;
	}
};
class Queue{
private:
	Node* front;
	Node* rear;
public:
	Queue(){
		front=rear=NULL;
	}
	~Queue(){
		Node* tmp;
		while(front){
			tmp=front;
			front=front->next;
			delete tmp;
		}
	}
	bool isEmpty(){
		return front==NULL;
	}
	void enQueue(int x){
		Node *tmp;
		tmp=new Node(x);
		if(isEmpty()){
			front=rear=tmp;
		}
		else{
			rear->next=tmp;
			rear=tmp;
		}
	}
	bool deQueue(int *px){
		if(isEmpty())	return false;
		else{
			*px=front->data;
			Node *tmp;
			tmp=front;
			front=front->next;
			delete tmp;
			if(front==NULL)	
				rear=NULL;
			return true;
		}
	} 
}; 

int main(){
	Queue q;
	q.enQueue(11);
	q.enQueue(22);
	q.enQueue(33);
	q.enQueue(44);
	int x;
	q.deQueue(&x);
	cout<<x<<endl;
	q.deQueue(&x);
	cout<<x<<endl;
	q.deQueue(&x);
	cout<<x<<endl;
	q.deQueue(&x);
	cout<<x<<endl;
	q.deQueue(&x);
	cout<<x<<endl;
	return 0;
}
  • C++ STL
#include <iostream>
#include <queue>
using namespace std;

int main(){
	queue<int> q;
	q.push(11);
	q.push(22);
	int x;
	x=q.front();
	cout<<x<<endl;
	q.pop();
	x=q.front();
	cout<<x<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

吉大秦少游

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

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

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

打赏作者

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

抵扣说明:

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

余额充值