线性表(特殊)-Queen(队列)

 typedef struct Qnode{
    int elem;
    struct Qnode *next;
}Qnode;

typedef struct queueList{
    struct Qnode *head;//队列的头指针
    struct Qnode *end;//队列的尾指针
}queueList;

创建队列

void createQueue(queueList *q) {
    q->head=q->end=(Qnode *)malloc(sizeof(Qnode));
    if(!q->head)
    {
        printf("创建头尾结点失败!");
        return;
    }
    q->end->next=NULL;
}

判断队列是否是空

int isEmptyQueue(queueList *q) {
    if (q->head==NULL)return 1;//头结点为空,队列空
    else return 0;
}

获取队列第一个元素

int getFirstQueue(queueList q) {
    if (q.head == NULL)
    {
         printf("队列空!");
         return 0;
    }

    return q.head->elem;
}

元素出队

int popQueue(queueList *q) {
    if (isEmptyQueue(q)) //空队列
        return 0;
    Qnode *p = q->head;//p指向头结点
    q->head = p->next;//头结点指向前头结点的下一位
    p->next = NULL;
    int value = p->elem;
    free(p);
    if (q->head == NULL)q->end = NULL;//头结点为空说明全部出队尾结点置空
    return value;
}

元素入队

int pushQueue(queueList *q,int value) {
    Qnode *newp = (Qnode *) malloc(sizeof(Qnode));
    if (newp == NULL)
    {
        printf("开辟空间失败!");
        return 0;
    }
    newp->elem=value;
    newp->next=NULL;
    if (q->end==NULL)//队尾指针为空
    {
        q->end = newp;
    }
    else //修改队尾指针
    {
        q->end->next=newp;
        q->end=newp;
    }
    if (q->head==NULL) //队头指针为空,说明在之前元素全部出队或者第一次入队
    {
        q->head=newp;
    }
    return 1;
}

遍历队列

void scanQueue(queueList *q)
{
    if(isEmptyQueue(q))
    {
        printf("队列空!");
        return 0;
    }
    Qnode *p=(Qnode *)malloc(sizeof(Qnode));
    p=q->head;
    while(p!=NULL)
    {
         printf("%3d->", p->elem);
         p = p->next;
    }
}

 

posted on 2021-11-03 16:30  Y-flower  阅读(100)  评论(0)    收藏  举报

导航