Queue 链表

#include "stdafx.h"
#include <windows.h>
#include <ctype.h>

typedef char ElemType;

typedef struct _QNode
{
	ElemType data;
	struct _QNode *next;
}QNode, *QueuePtr;

typedef struct  
{
	QueuePtr front;
	QueuePtr rear;
}LinkQueue;

int InitQueue( LinkQueue *q )
{
	q->front = q->rear = (QueuePtr)malloc(sizeof(QNode));
	if ( !q->front )
	{
		exit(0);
	}
	q->front->next = NULL;
}

int EnQueue( LinkQueue *q, ElemType e )
{
	QueuePtr p;
	p = ( QueuePtr )malloc( sizeof(QNode) );
	if ( !q->front )
	{
		exit( 0 );
	}

	p->data = e;
	p->next = NULL;
	q->rear->next = p;
	q->rear = p;
}

int OutQueue( LinkQueue *q, ElemType* e )
{
	QueuePtr p;

	if ( q->front == q->rear ) /*队列为空,返回*/
	{
		printf("the queue is null \n ");
		return 0;
	}

	p = q->front->next;
	*e = p->data;
	q->front->next = p->next;
	
	if (q->rear == p )
	{
		q->rear = q->front; /*如果队头就是队尾,则修改队尾指针*/
	}

	free( p );

}

int main()
{
	ElemType e;
	LinkQueue  q;
	InitQueue(&q);           /*初始化一个队列q*/
	printf("Please input a string into a queue\n");
	scanf("%c",&e);
	while(e!='@'){
		EnQueue(&q,e);   /*向队列中输入字符串,以@表示结束*/ 
		scanf("%c",&e);
	}
	printf("The string into the queue is\n");
	while(q.front != q.rear){   /*将队列中的元素出队列,并打印在屏幕上*/
		OutQueue(&q,&e);
		printf("%c",e);
	}
	printf("\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值