面试题之队列简单详述

          队列是一种数据结构,可以在队列的一端插入元素而在队列的另一端删除元素,它有以下特点:

(1)允许删除的一端称为队头(front)。

(2)允许插入到一端称为队尾(rear)。

(3)当队列中没有元素时称为空队列。

(4)队列亦称作先进先出(First In First Out)的线性表,简称为FIFO表。队列的修改依据先进先出的原则,新来的成员总是加入队尾(即不能中间插入),每次离开的成员总是队头的成员(不允许中途离队)。

         队列的实现可以使用链表和数组,本题中采用单链表来实现队列。先定义队列和队列的节点。

typedef struct _Node
{
	int data;
	struct _Node *next;  //指向下一个节点
}node;

typedef struct _Queue
{				//node表示队列中的每个节点元素
	node *front;	//队头
	node *rear;		//队尾
}MyQueue;
在进行编程之前,首先要构造一个空的队列,代码如下:

//构造空的队列
MyQueue *CreateMyQueue()
{
	MyQueue *q = (MyQueue *)malloc(sizeof(MyQueue));
	q->front = NULL;   //把队首指针很队尾指针都置为空
	q->rear = NULL;

	return q;
}
入队   由入队特点,入队操作是在队尾一端进行插入的。代码如下:

//入队,从队尾一端插入节点
MyQueue *enqueue(MyQueue *q, int data)
{
	node *newP = NULL;
	newP = (node *)malloc(sizeof(node));//新建节点
	newP->data = data;
	newP->next = NULL;
	
	if(NULL == q->rear)
	{				//若队列为空,新节点即使队首优势队尾
		q->front = q->rear = newP;
	}
	else
	{				//新节点放在队尾,
		q->rear->next = newP;
		q->rear = newP;			//队尾指针指向新节点
	}
	return q;
}

出队,出队与入队操作不同,它是在队首一端进行删除的。代码如下:

//出队,从队头一端删除节点
MyQueue *dequeue(MyQueue *q)
{
	node *pnode = NULL;
	pnode = q->front;	//指向队头

	if(NULL == pnode)	//队列为空
	{
		printf("Empty queue!\n");
	}
	else		
	{
		q->front = q->front->next;	//新队头
		if(NULL == q->front)		//若删除后队列为空,对rear置空
		{
			q->rear = NULL;
		}
		free(pnode);			//删除原队头节点
	}

	return q;
}
测长。代码如下:

//队列的测长
int GetLength(MyQueue *q)
{
	int nlen = 0;
	node *pnode = q->front;

	if(NULL != pnode)
	{
		nlen = 1;
	}
	while(pnode != q->rear)
	{
		nlen++;
		pnode = pnode->next;
	}

	return nlen;
}
打印,代码如下:

//队列的打印
void PrintMyQueue(MyQueue *q)
{
	node *pnode = q->front;

	if(NULL == pnode)
	{
		printf("Empty Queue!\n");
		return ;
	}
	printf("data: ");
	while(pnode != q->rear)
	{
		printf("%d ", pnode->data);
		pnode = pnode->next;
	}
	printf("%d", pnode->data);
}

下面是对上面各个函数的简单测试:

int main()
{
	int nlen = 0;
	MyQueue *hp = CreateMyQueue(); //建立队列
	enqueue(hp, 1);
	enqueue(hp, 2);
	enqueue(hp, 3);
	enqueue(hp, 4);			//入队
	nlen = GetLength(hp);	//获得队列长度
	printf("nlen = %d\n", nlen);
	PrintMyQueue(hp);
	printf("\n");

	dequeue(hp);			//出队两次
	dequeue(hp);
	nlen = GetLength(hp);
	printf("\nnlen = %d\n", nlen);

	PrintMyQueue(hp);
	printf("\n");

	return 0;
}
测试结果:

nlen = 4
data: 1 2 3 4

nlen = 2
data: 3 4
Press any key to continue



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值