顺序队列和链式队列

顺序队列

#include <stdio.h>  
#include <stdlib.h>

#define MAX 5
//顺序队列
typedef struct{
	int data[MAX];
	int front,rear;
}SqQueue;

void initQueue(SqQueue &Q){
	Q.front=Q.rear=0;
}

bool isEmpty(SqQueue &Q){
	return Q.front==Q.rear;
}

bool isFull(SqQueue &Q){
	return ((Q.rear+1)%MAX)==Q.front; 
}

void enQueue(SqQueue &Q,int e)
{
	if(isFull(Q))  
        printf("queue is full:\n"); 
	Q.data[Q.rear]=e;
	Q.rear=(Q.rear+1)%MAX;
}

int deQueue(SqQueue &Q)
{
	if(isEmpty(Q))  
        printf("queue is empty:\n"); 
	int e;
	e=Q.data[Q.front];
	Q.front=(Q.front+1)%MAX;
	return e;
}

void print(SqQueue &Q){
	int i;
	printf("Print the queue:\n"); 
	for(i=Q.front;i%MAX<Q.rear;i++)
		printf("%3d",Q.data[i]);
	printf("\n");
}

void main(){
	SqQueue q;
	int e;
	initQueue(q);
	enQueue(q,1);
	enQueue(q,3);
	enQueue(q,5);
	print(q);
	e=deQueue(q);
	printf("dequeue is %3d\n",e);
	print(q);
}


链式队列

#include<stdio.h>
#include<malloc.h>
 
typedef int ElemType;
typedef struct LinkNode{
	ElemType data;
	LinkNode *next;
}LinkNode;
typedef struct {
	LinkNode *front,*rear;
}LinkQueue;


void initQueue(LinkQueue &Q){
	Q.front=Q.rear=(LinkNode *)malloc(sizeof(LinkNode));
	Q.front->next=NULL;

}

bool isEmpty(LinkQueue Q){
	if(Q.front==Q.rear)
		return true;
	else return false;
}

void enQueue(LinkQueue &Q,ElemType x){
	LinkNode *s=(LinkNode *)malloc(sizeof(LinkNode));
	s->data=x;s->next=NULL;
	Q.rear->next=s;
	Q.rear=s;
}
/*从队列中删除一个元素*/
int delQueue(LinkQueue &Q)
{
	int temp;
	if(Q.front==Q.rear) return false;
	LinkNode *p=Q.front->next;
	temp=p->data;
	Q.front->next=p->next;
	if(Q.rear==p){
		Q.rear=Q.front;
	}
	free(p);
    return temp;    /*返回被删除的队首元素值*/
}

void print(LinkQueue &Q){
	LinkNode *top=Q.front->next;
	while(top){
		printf("%3d",top->data);
		top=top->next;
	}
}
void main(){
	LinkQueue q;
    int a[8]={3,8,5,17,9,30,15,22};
    int i;
    initQueue(q);
    for(i=0;i<8;i++)
    {
       enQueue(q,a[i]);
    }
	print(q);
    printf("delnode is %d\n",delQueue(q));
	printf("delnode is %d\n",delQueue(q));
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值