#include <stdio.h>
#include <stdlib.h>
/*
**队列是只允许在一端进行插入操作,而在另一端进行删除操作的
**线性表
**队列是一种先进先出的线性表
**队列既可以用链表实现,也可以用顺序表实现
**跟栈相反的是,栈一般我们用顺序表来实现 ,二队列我们常用链表
**来实现,简称为链队列
*/
typedef char ElemType;
/*
**队列的结构
*/
typedef struct QNode
{
ElemType data;
struct QNode *next;
}QNode,*QueuePrt;
/*
**将对头指针指向链队列的头结点,而队尾指针指向终端结点
**头结点不是必要的,但为了方便操作,我们加上了
**空队列时,front和rear都指向头结点
*/
typedef struct
{
QueuePrt front,rear;//对头,队尾
}LinkQueue;
/*
**创建一个队列
**一是在内存中创建一个头结点,
**二是将队列的头指针和为指针都指向这个生成的头结点
*/
void InitQueue(LinkQueue *q)
{
q->front=q->rear=(QueuePrt)malloc(sizeof(QNode));
if(!q->front)
exit(0);
q->front->next=NULL;
}
/*
**入队列的操作
*/
void InsertQueue(LinkQueue *q,ElemType e)
{
QueuePrt p;
p=(QueuePrt)malloc(sizeof(QNode));
if(p==NULL)
exit(0);
p->data=e;
p->next=NULL;
q->rear->next=p;
q->rear=p;
}
/*
**出队列操作
*/
void DeleteQueue(LinkQueue *q,ElemType *e)
{
QueuePrt p;
if(q->front==q->rear)
return;
p=q->front->next;
*e=p->data;
q->front->next=p->next;
if(q->rear==p)
q->rear=q->front;
free(p);
}
/*
**销毁队列
*/
void DestroyQueue(LinkQueue *q)
{
while(q->front)
{
q->rear=q->front->next;
free(q->front);
q->front=q->rear;
}
}
int main()
{
LinkQueue q;
char c,e;
InitQueue(&q);
printf("请输入一串字符,以#作为结束标志:\n");
scanf("%c",&c);
while(c!='#')
{
while((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
{
InsertQueue(&q,c);
scanf("%c",&c);
}
if(c==32)
{
InsertQueue(&q,c);
}
else if(c=='#')
{
printf("字符的输出为:\n");
while(q.front!=q.rear)
{
DeleteQueue(&q,&e);
if(e!=32)
{
printf("%c",e);
}
else
{
printf(" ");
}
}
break;
}
scanf("%c",&c);
}
return 0;
}
数据结构与算法之队列
最新推荐文章于 2022-10-25 21:30:10 发布