数据结构之表(7)队列的顺序实现

代码:

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

# define MAXSIZE  2 /*队列长度*/

/*存储结构*/
typedef struct queue_tag {
	int * front; /*指向队首*/
	int * rear ; /*指向队尾*/
}ds_queue;

/*初始化*/
void ds_init(ds_queue * q) {
	int * temp ;
	temp = (int *)malloc(MAXSIZE * sizeof(int)) ;
	if(!temp)
		exit(0) ;
	q->front = temp ;
	q->rear = q->front ; /*队首和队尾指向同一个位置*/
}

/*是否为空*/
int ds_isEmpty(ds_queue * q) {
	if(q->front == q->rear)
		return 1 ; /*空,返回1*/
	else
		return 0 ;
}

/*入队*/
void ds_enqueue(ds_queue * q,int elem) {
	if(q->rear - q->front == MAXSIZE) {
		printf("队列已满!\n") ;
		return ;
	}
	*(q->rear) = elem ; /*数据入队,将队尾指针后移一个位置*/
	++ q->rear ;
}

/*出队*/
int ds_dequeue(ds_queue * q) {
	if(ds_isEmpty(q)) {
		printf("队列为空\n") ;
		return 0;
	}
	else
	{
		int *temp ;
		int elem ;
		elem = *(q->front) ;

		/*将所有数据向前移动一个位置*/
		temp = q->front ;
		for( ; temp < q->rear ; *(temp) = *(temp + 1),temp ++) ;
		--q->rear ;
		return elem ;
	}
}

测试程序

int main() 
{
	ds_queue q ;
	ds_init(&q) ;
	printf("入队顺序为1,2,3(队列长度为2)\n") ;
	ds_enqueue(&q,1) ;
	ds_enqueue(&q,2) ;
	ds_enqueue(&q,3) ;
	printf("出队顺序:") ;
	printf("%d ",ds_dequeue(&q)) ;
	printf("%d ",ds_dequeue(&q)) ;
	ds_dequeue(&q) ;
	getchar() ;
	return 0 ;
}

结果

1

posted on 2011-04-29 10:55  codmer  阅读(358)  评论(0编辑  收藏  举报