基础数据结构--队列链表实现

代码已经过测试

#include 
#include 

//元素类型定义
typedef int elemType;

//队列链表节点
typedef struct qNode
{
	elemType data;
	struct qNode *next;
}qNode;

//队列链表
typedef struct qList
{
	qNode *front;
	qNode *rear;
}qList;

//建立队列
qList* createQList()
{
	qList *q = (qList*)malloc(sizeof(qList));
	if(!q) exit(-1);
	q->front = NULL;
	q->rear = NULL;
	return q;
}

//清空队列
int clearQList(qList *&q)
{
	if(!q) return -1;
	if(!q->front || !q->rear) return 0;
	qNode *temp = q->front;
	qNode *dropNode = NULL;
	while(temp != q->rear)
	{
		dropNode = temp;
		temp = temp->next;
		free(dropNode);
	}
	free(temp);
	temp = NULL;
	q->front = NULL;
	q->rear = NULL;
	return 1;
}

//销毁队列
void destroyQList(qList *&q)
{
	if(!q) return ;
	clearQList(q);
	free(q);
	q = NULL;
}

//向队列尾部加节点
int enQList(qList *&q, elemType e)
{
	if(!q) return -1;
	qNode *newNode = (qNode*)malloc(sizeof(qNode));
	if(!newNode)
	{
		return -1;
	}
	newNode->data = e;
	newNode->next = NULL;
	if(q->rear)
	{
		q->rear->next = newNode;
		q->rear = newNode;
	}
	else
	{
		q->front = q->rear = newNode;
	}
	return 1;
}

//在队列头部删减节点
int deQList(qList *&q, elemType &e)
{
	if(!q || !q->front || !q->rear) return -1;
	qNode *dropNode = q->front;
	e = dropNode->data;
	q->front = q->front->next;
	if(dropNode == q->rear)
		q->rear = NULL;
	free(dropNode);
	dropNode = NULL;
	return 1;
}

//打印队列
void showQList(qList *q)
{
	if(!q)
	{
		printf("error: no queue!\n");
		return;
	}
	if(!q->front || !q->rear)
	{
		printf("empty list!\n");
		return ;
	}
	qNode *temp = q->front;
	while(temp != q->rear)
	{
		printf("%d ",temp->data);
		temp = temp->next;
	}
	printf("%d\n",temp->data);
}

//测试代码
int main()
{
	qList *q = createQList();
	enQList(q,34);
	enQList(q,396);
	enQList(q,414);
	enQList(q,5);
	enQList(q,6577);
	enQList(q,1);
	showQList(q);

	elemType e=0;
	deQList(q,e);
	printf("e: %d\n",e);
	showQList(q);

	clearQList(q);
	showQList(q);

	destroyQList(q);
	showQList(q);

	getchar();
	return 0;
}


你可能感兴趣的:(数据结构,链表,数据结构,线性表)