队列的应用

// 队列的基本操作:实现一个链队列,任意输入一串字符,以@为结束标志,然后将队列中的元素逐一取出,打印在屏幕上
#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 ;
}

你可能感兴趣的:(队列的应用)