数据结构-队列(链式队列实现)

链式队列中结点的结构体定义:

typedef struct qnode{
	DataType data;
	struct qnode *next;
}LQNode;

为了方便参数调用,通常把链式队列的头指针front和队尾指针rear定义为下面的格式:

typedef struct{
	LQNode *front;
	LQNode *rear;
}LQueue;

链式队列操作的实现:
(1),queue init

void QueueInitiate(LQueue *Q)
{
	Q->rear = NULL;
	Q->front = NULL;
}

(2),judge the queue is NULL or not
not NULL return 1, NULL return 0

int QueueNotEmpty(LQueue Q)
{
	if (Q.front == NULL)
	{
		return 0;
	}
	else{
		return 1;
	}
}

(3),insert queue
insert the data_item into the end of queue

void QueueAppend(LQueue *Q, DataType x)
{
	LQNode *p;
	p = (LQNode *)malloc(sizeof(LQNode));

	p->data = x;
	p->next = NULL;

	if (Q->rear != NULL)
	{
		Q->rear->next = p;
	}
	Q->rear = p;
	if (Q->front == NULL)
	{
		Q->front = p;
	}
}

(4),delete queue item

int QueueDelete(LQueue *Q, DataType *d)
{
	LQNode *p;
	if(Q->front == NULL)
	{
		printf("queue have empty, no item could be delete");
		return 0;
	}
	else{
		*d = Q->front->data;
		p  = Q->front;
		Q->front = Q->front->next;
		if (Q->front == NULL)
		{
			Q->rear = NULL;
		}
		
		free(p);
		return 1;
	}
}

(5),Get the head item of queue

int QueueGet(LQueue *Q, DataType *d)
{
    LQueue *p = NULL;
	if (Q->front == NULL)
	{
		printf("Queue have empty, no item could be get!");
		return 0;
	}
	else{
	    p = Q->front->next;
		*d = p->data;
		Q->front->next = p->next;

		if (Q->rear == p)
		{
			Q->rear = Q->front;
		}
		free(p);
		return 1;
	}
}

(6),Destroy queue

void Destroy(LQueue Q)
{
	LQNode *p, *p1;
	
	p = Q.front;
	while (p!= NULL)
	{
		p1 = p;
		p = p->next;
		free(p1);
	}
}

你可能感兴趣的:(数据结构,数据结构-队列(链式队列实现))