当前位置:   article > 正文

数据结构之队列(一)(C语言版)_c语言连队列求长度

c语言连队列求长度

博主好久没发数据结构知识点的学习了,我们今天来看看队列的基础知识点吧,后几篇文章博主再来分享一些队列的实际应用。队列平时我们用的最多的是链队,顺序队列因为浪费空间,不推荐使用。这篇文章主要讲链队。好啦,废话不多说,直接上干货。

1.定义数据类型:

typedef struct Qnode
{
    ElemType data;//其中数据域data为抽象元素类型
    struct Qnode *next;//其中next为指针类型 
}Qnode,*QueuePtr;//其中,Qnode为结点类型, QueuePtr:指向Qnode的指针类型
typedef struct

{  Qnode *front;//头指针

    Qnode *rear;//尾指针

}LinkQueue;

2.初始化链队

typedef int Status;

Status InitQueue(LinkQueue *Q)
{
    
    Q->front=(QueuePtr)malloc(sizeof(QNode));///给头尾指针分配内存,让队列中的头尾指针指向                                                                                同一个内存
    Q->rear=Q->front;
    if(!Q->front) exit(OVERFLOW);
    Q->front->next=NULL;
    return OK;
}

3.进队:

typedef int QElemType;

Status EnQueue(LinkQueue *Q,QElemType e)
{
    QNode *p;
    p=(QNode *)malloc(sizeof(QNode));
    if(!p) exit(OVERFLOW);
    p->data=e;//先赋值
    p->next=NULL;
    Q->rear->next=p;//再后移
    Q->rear=p;
    return OK;
}

4.出队:

typedef int Status;

Status DeQueue(LinkQueue *Q,QElemType *e)
{
    QNode *p;
    if(Q->front==Q->rear)
        return ERROR;
    p=Q->front->next;
    *e=p->data;//先赋值
    Q->front->next=p->next;//再后移
    if(Q->rear==p)//到达队列末尾
        Q->rear=Q->front;
    free(p);
    return OK;
}

5.打印队列元素:

void ShowQueueElement(LinkQueue Q)
{
    QNode *p;
    p=Q.front->next;
    while(p!=NULL)
    {
        printf("%d  ",p->data);
        p=p->next;
    }
    printf("\n");
}
6.求队列长度:

int QueueLength(LinkQueue Q)

{ int count=0;

QNode *p;

p=Q.front->next;

while(p!=NULL)

{ count++; p=p->next; }

return count;

}

7.获取队列头元素:

Status GetHead(LinkQueue Q,QElemType *e)

{ QNode *p;

p=Q.front;

if(Q.front==Q.rear)

return ERROR;

*e=p->next->data;

return OK;

}

8.清空队列:

Status ClearQueue(LinkQueue *Q)
{
    QNode *p,*q;
    p=Q->front->next;
    Q->front->next=NULL;
    while(p)
    {
        q=p->next;
        free(p);
        p=q;
    }
    Q->front=Q->rear;
    return OK;
}
9.判断是否为空队列

Status QueueEmpty(LinkQueue *Q)

{ if(Q->front->next==NULL)

return TRUE;

else return FALSE;

}

10.销毁队列:

Status DestroyQueue(LinkQueue *Q)
{
    while(Q->front)
    {
         Q->rear=Q->front->next;///队尾指针始终指向队头指针的下一个元素
        free(Q->front);
        Q->front=Q->rear;///调整队头指针
    }
    return OK;
}

好啦,今天关于队列的基础知识的分享就到这里啦。看到这,还不上机体验一下,hhh。

本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览.


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/884894
推荐阅读
相关标签
  

闽ICP备14008679号