天之道

享受编程的乐趣。
posts - 118, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

队列的应用

Posted on 2012-03-03 18:42 hoshelly 阅读(298) 评论(0)  编辑 收藏 引用 所属分类: DS && Algorithm
//队列的基本操作:实现一个链队列,任意输入一串字符,以@为结束标志,然后将队列中的元素逐一取出,打印在屏幕上
#include<stdio.h>
#include
<stdlib.h>
#include
<conio.h>
typedef 
char ElemType;
typedef 
struct QNode
{
    ElemType data;
    
struct QNode *next;
}QNode,
*QueuePtr;
typedef 
struct{
    QueuePtr front; 
//队头指针
    QueuePtr rear;  //队尾指针
}LinkQueue;

initQueue(LinkQueue 
*q) //创建一个头结点,队头队尾指针指向该结点
{
    q
->front=q->rear=(QueuePtr)malloc(sizeof(QNode));

    
if(!q->front) exit(0);
    q
->front->next=NULL;
}

EnQueue(LinkQueue 
*q,ElemType e)
{
    QueuePtr p;
    p
=(QueuePtr)malloc(sizeof(QNode));
    
if(!q->front) exit(0);
    p
->data=e;      //数据e入列
    p->next=NULL;
    q
->rear->next=p;
    q
->rear=p;
}

DeQueue(LinkQueue 
*q,ElemType *e)//如果队列q不为空,删除q的队头元素,用e返回其值
{
    QueuePtr 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);
}

int main()
{
    ElemType e;
    LinkQueue q;
    initQueue(
&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)
    {
        DeQueue(
&q,&e);
        printf(
"%c",e);
    }

    printf(
"\n");
    getche();
    
return 0;
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理