链式队列 无表头

来源:互联网 发布:网络用语arp是什么意思 编辑:程序博客网 时间:2024/05/19 20:00
#ifndef QUEUE2_H_INCLUDED
#define QUEUE2_H_INCLUDED


//没有头结点  好处是出队列的时候单节点表不用单独考虑    但是插入时候要单独考虑空队列


typedef int elem;


struct node
{
    elem data;
    struct node*next;
};


typedef struct
{
    struct node*front;
    struct node*rear;
}queue;


queue Initial(queue Q)
{
    Q.front=Q.rear=NULL;
    return Q;
}


int length(queue Q)
{
    int len;
    for (len=0;Q.front!=NULL;Q.front=Q.front->next)
        len++;
    return len;
}


queue EnQueue(queue Q,elem x)//从队尾插入
{
    struct node * p;
    p=(struct node*)malloc(sizeof(struct node));
    p->data=x;
    p->next=NULL;


    if (Q.front!=NULL)
    {
        Q.rear->next=p;     //空队列不能引用next
        Q.rear=Q.rear->next;
    }
    else
    {
        Q.rear = p;
        Q.front=p;
    }


    return Q;
}


queue DeQueue(queue Q,elem *x)//从队首删除
{
    if (Q.front==NULL)
    {
        printf("NULL queue\n");
        exit(0);
    }


    *x=Q.front->data;
    struct node*p=Q.front;
    Q.front=p->next;
    free(p);
    return Q;
}


void Print(queue Q)
{
    printf("queue has %d elements\n",length(Q));
    while (Q.front)
    {
        printf("%d\t",Q.front->data);
        Q.front=Q.front->next;
    }
    printf("\n");
}


#endif // QUEUE2_H_INCLUDED
原创粉丝点击