队列的基本操作

本文介绍了一个简单的队列数据结构的实现方法,包括初始化队列、插入元素、删除元素及显示队列等功能。通过C语言代码示例展示了如何进行队列的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include<iostream>
using namespace std;
typedef struct node
{
	char data;
	struct node *link;//指向后缀结点的指针
};
typedef struct Queue
{
	node *first,*rear;//定义队列的头和尾指针
};
Queue * InsertQueue(Queue *Q,char value)
{
	node*newNode=(node*)malloc(sizeof(node));
	newNode->data=value;
	newNode->link=NULL;

	if(Q->first==NULL)
		Q->first=Q->rear=newNode;
	else
	{
		Q->rear->link=newNode;
		Q->rear=newNode;
	}
	return Q;
}
Queue * DeleteQueue(Queue *Q)
{
	node*ptemp;
	if(Q->first==NULL)
		cout<<"队列已空!"<<endl;
	else
	{
		ptemp=Q->first;
		if(Q->first==Q->rear)
		{
			Q->first=NULL;
			Q->rear=NULL;
		}
		else
			Q->first=Q->first->link;
		free(ptemp);
	}
	return Q;
}
Queue * InitQueue()
{
	char ch;
	node*newNode;
	Queue *QL=(Queue*)malloc(sizeof(Queue));//初始化队列
	QL->first=(node*)malloc(sizeof(node));//队列中的第一个元素,头尾指针均指向该结点
	QL->first->link=NULL;
	QL->rear=QL->first;
	cout<<"请输入字符串并回车,初始化队列如下:"<<endl;
	ch=getchar();
	while(ch!='\n')
	{
		newNode=(node*)malloc(sizeof(node));
		newNode->data=ch;
		newNode->link=NULL;

		if(QL->first==NULL)
			QL->first=QL->rear=newNode;
		else
		{
			QL->rear->link=newNode;
			QL->rear=newNode;
		}
		ch=getchar();
	}
	return QL;	
}
int length(Queue *Q)
{
	int count=0;
	node*ptemp=Q->first;
	while(ptemp->link!=NULL)
	{
		count++;
		ptemp=ptemp->link;
	}
	return count;
}
void DisplayQueue(Queue *QL)
{
	node*ptemp;
	ptemp=QL->first->link;
	if(ptemp==NULL)
		cout<<"队列已空!"<<endl;
	while(ptemp!=NULL)
	{
		cout<<ptemp->data;
		ptemp=ptemp->link;
		if(ptemp!=NULL)
			cout<<"——> ";	
	}
	cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
    Queue *Q=InitQueue();
	DisplayQueue(Q);

	cout<<"After InsertQueue():"<<endl;
	InsertQueue(Q,'c');
	cout<<"在队列尾部插入字符c后的元素有:"<<endl;
	DisplayQueue(Q);

	cout<<"After DeleteQueue():"<<endl;
	DeleteQueue(Q);
	cout<<"删除队列头部元素后,队列中的元素有:"<<endl;
	DisplayQueue(Q);
	
	cout<<"队列中元素的数目是:"<<length(Q)<<endl;

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值