队列的简单实现

顺序表的实现:

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

#define MaxSize 100
typedef int ElemType;

typedef struct{
	ElemType data[MaxSize];
	int front, rear;
}SQUEUE;

void initQueue(SQUEUE *sq)
{
	sq->rear = sq->front = 0;
}

int EnQueue(SQUEUE *sq, ElemType x)
{
	if((sq->rear + 1) % MaxSize == sq->front)
	{
		printf("\n queue is full");
		return 0;
	}
	sq->rear = (sq->rear + 1) % MaxSize;
	sq->data[sq->rear] = x;
	return 1;
}

int Empty(SQUEUE *sq)
{
	return (sq->rear == sq->front) ? 1 : 0;
}

int OutQueue(SQUEUE *sq, ElemType *x)
{
	if(Empty(sq))
	{
		printf(" \n queue is free");
		return 0;
	}
	sq->front = (sq->front + 1) % MaxSize;
	*x = sq->data[sq->front];
	return 1;
}

int getHead(SQUEUE *sq, ElemType *x)
{
	if(Empty(sq))
	{
		printf("\n queue is free");
		return 0;
	}
	*x = sq->data[(sq->front + 1) % MaxSize];
	return 1;
}

int main()
{
	ElemType x;
	SQUEUE sq;
	initQueue(&sq);
	EnQueue(&sq, 10);
	getHead(&sq, &x);
	printf("%d\n", x);
	EnQueue(&sq, 20);
	getHead(&sq, &x);
	printf("%d\n", x);
	system("pause");
	return 0;
}


 

链表的实现:

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

typedef int ElemType;
typedef struct qnode{
	ElemType data;
	struct qnode *next;
}QTYPE;

typedef struct qptr{
	QTYPE *front, *rear;
}SQUEUE;

SQUEUE LQ;

void initQueue(SQUEUE *lq)
{
	QTYPE *p;
	p = (QTYPE*)malloc(sizeof(QTYPE));
	p->next = NULL;
	lq->front = lq->rear = p;
}

int EnQueue(SQUEUE *lq, ElemType x)
{
	QTYPE *s;
	s = (QTYPE*)malloc(sizeof(QTYPE));
	s->data = x;
	s->next = lq->rear->next;
	lq->rear->next = s;
	lq->rear = s;
	return 1;
}

int Empty(SQUEUE *lq)
{
	return (lq->front == lq->rear ? 1 : 0);
}

int OutQueue(SQUEUE *lq, ElemType *x)
{
	QTYPE *p;
	if(Empty(lq))
	{
		printf("\n queue is free");
		return 0;
	}
	p = lq->front->next;
	*x = p->data;
	lq->front->next = p->next;
	if(lq->front->next == NULL)
		lq->rear = lq->front;
	free(p);
	return 1;
}

int getHead(SQUEUE *lq, ElemType *x)
{
	if(Empty(lq))
	{
		printf("\n queue is free");
		return 0;
	}
	*x = lq->front->next->data;
	return 1;
}

int main()
{
	ElemType x;
	initQueue(&LQ);
	EnQueue(&LQ, 10);
	getHead(&LQ, &x);
	printf("%d\n", x);
	EnQueue(&LQ, 20);
	getHead(&LQ, &x);
	printf("%d\n", x);
	OutQueue(&LQ, &x);
	printf("%d\n", x);
	system("pause");
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值