C语言编程队列的实现

<span style="font-size:24px;">queue.c</span>
<span style="font-size:24px;">功能函数:</span>
<span style="font-size:24px;"></span><pre name="code" class="objc">#include "queue.h"
static void CopyToNode(Item item,Node *pn)
{
	pn->item = item;
}

static void CopyToItem(Node *pn, Item *pi)
{
	*pi = pn->item;
}
/* 把队列初始化为空,就是设置尾指针为NULL并设置项数(items成员)为0 */ 
void InitializeQueue(Queue *pq)
{
	pq->front = pq->rear = NULL;
	pq->items = 0;
}

bool QueueIsFull( const Queue *pq)
{
	return (pq->items == MAXQUEUE);
}

bool QueueIsEmpty( const Queue *pq)
{
	return (pq->items == 0);
}

int QueueItemCount(const Queue *pq)
{
	return pq->items;
}

bool EnQueue( Item item,Queue *pq)
{
	Node * pnew;
	if (QueueIsFull(pq))
	{
		return false;
	}
	pnew = (Node *)malloc(sizeof(Node));
	if (pnew == NULL)
	{
		fprintf(stderr, "Unable to allocate memory!\n");
		exit(1);
	}
	CopyToNode(item,pnew);
	pnew->next = NULL;
	if (QueueIsEmpty(pq))
	{
		pq->front = pnew;			/* 项目位于队列首端 */
	}
	else
	{
		pq->rear->next = pnew;				/* 链接到队列尾端 */
	}
	pq->rear = pnew;							/* 记录队列尾端的位置 */
	pq->items++;							/* 队列项目个数增1 */
	return true;
}

bool DeQueue( Item *pitem, Queue *pq)
{
	Node *pt;
	
	if (QueueIsEmpty(pq))
	{
		return false;
	}
	CopyToItem(pq->front,pitem);
	pt = pq->front;
	pq->front = pq->front->next;
	free(pt);
	pq->items--;
	if (pq->items == 0)
	{
		pq->rear = NULL;
	}
	return true;
}

void EmptyTheQueue(Queue *pq)
{
	Item dummy;
	while (!QueueIsEmpty(pq))
	{
		DeQueue(&dummy,pq);
	}
}


<span style="font-size:24px;">测试程序:</span>
<span style="font-size:24px;"></span><pre name="code" class="objc">#include "queue.h"

int main(void)
{
	Queue line;
	Item temp;
	char ch;

	InitializeQueue(&line);
	puts("Testing the queue interface, type a to add a value,");
	puts("type d to delete a value ,and type q to quit");
	while((ch =getchar())!= 'q')
	{
		if (ch !='a' && ch != 'd')
		{
			continue;
		}
		if (ch == 'a')
		{
			printf("integer to add:\n");
			scanf("%d",&temp);
			if (!QueueIsFull(&line))
			{
				printf("Putting %d into queue\n",temp);
				EnQueue(temp,&line);
			}
			else
			{
				puts("Queue is full");
			}
		}
		else
		{
			if (QueueIsEmpty(&line))
			{
				puts("没有了");
			}
			else
			{
				DeQueue(&temp,&line);
				printf("删除了%d\n",temp);
			}
		}
		printf("%d item in queue\n",QueueItemCount(&line));
		puts("type a to add ,d to delete, q to quit:");
	}
	EmptyTheQueue(&line);
	puts("bye!");
}


<span style="font-size:24px;">
</span>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。