1. 程式人生 > >《資料結構》嚴蔚敏 順序儲存實現佇列 演算法3_4_1

《資料結構》嚴蔚敏 順序儲存實現佇列 演算法3_4_1

這個的實現和前面的棧大同小異,就不多敘述了

在這裡插入圖片描述

// queue
//除了這種還有雙端佇列

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

#define OK 1
#define ERROR 0

#define INIT_SIZE 100
#define INCRESMENT 10

typedef int ElemType;
typedef int Status;

typedef struct 
{
	ElemType * queue_head;
	ElemType * queue_rear;

	int queue_size;

}Queue;

//初始化佇列

Status
InitQueue(Queue * q)
{

	q->queue_head = (ElemType *)malloc(INIT_SIZE * sizeof(ElemType));
	if(q->queue_head == NULL)
		return ERROR;

	q->queue_rear = q->queue_head; 
	q->queue_size = INIT_SIZE;

	return OK;

}

//銷燬佇列

Status
DestoryQueue(Queue * q)
{
	if(q->queue_size > 0)
	{
		q->queue_size = 0;
	}
	
	free(q);
	q = NULL;

	return OK;
}


//清空佇列
Status
ClearQueue(Queue *q)
{
	while(q->queue_head != q->queue_rear)
		q->queue_head ++;
	
	q->queue_size = 0;

	return OK;

}


//判斷佇列是否為空
Status
EmptyQueue(Queue q)
{
	if(q.queue_head == q.queue_rear)
		return OK;
	else
		return ERROR;

}


//返回佇列的長度
int
LengthQueue(Queue q)
{
	return q.queue_rear - q.queue_head;
	
}


//在隊尾插入元素
//疑問:隊尾指標在未插入前是正好指向還是什麼樣的指向,我先把它按棧一樣的算吧
//對,就是一樣的
Status
InsertQueue(Queue * q,ElemType e)
{
	if( q->queue_rear - q->queue_head >= INIT_SIZE )
	{
		q->queue_head = (ElemType *)realloc
		(q,(q->queue_size+INCRESMENT)*sizeof(ElemType));

		q->queue_rear = q->queue_head;
		q->queue_size += INCRESMENT;
	}
	*q->queue_rear = e;
	q->queue_rear ++;

	return OK;
}


//在隊頭刪除元素

Status
DeleteQueue(Queue * q)
{
	if(q->queue_head == q->queue_rear)
		return ERROR;

	q->queue_head ++;

	q->queue_size --;

	return OK;

}


//獲取佇列頭的元素的值
Status
GetTop(Queue q,ElemType *e)
{
	if(q.queue_head == q.queue_rear)
		return ERROR;
	else
		*e = *(q.queue_head);
	

	return OK;

}


//遍歷佇列
Status
TraverseQueue(Queue q,void(*visit)(ElemType *c))
{
	ElemType* temp;
	temp = q.queue_head;
	while(temp != q.queue_rear)
	{
		visit(temp);
		temp ++;
	}

	printf("\n");

	return OK;

}

void
visit(ElemType *c)
{
	printf("%d ", *c);
}




int main(int argc, char const *argv[])
{
	Queue q;
	int head,length;
	InitQueue(&q);
	InsertQueue(&q,1);
	InsertQueue(&q,2);
	InsertQueue(&q,3);
	InsertQueue(&q,4);
	printf("after insert:\n");
	TraverseQueue(q,visit);

	DeleteQueue(&q);
	printf("after delete:\n");
	TraverseQueue(q,visit);

	GetTop(q,&head);

	printf("\nqueue_head element is: %d ",head);

	length = LengthQueue(q);
	printf("\nqueue length is %d\n", length);

	return 0;
}