队列的链式存储

与栈相反,队列是一种先进先出的线性表,它只允许在表的一端进行,而在另一端删除元素。

在队列中,允许插入的一端叫做队尾,允许删除的一端则称为队头。

链队列的操作即为单链表的插入和删除操作的特殊情况,只是尚需修改尾指针或头指针。

单链队列——队列的链式存储结构,如下所示。

 C++ Code 
1
2
3
4
5
6
7
8
typedef struct node
{
    int data;
    struct node *next;
}L,*Link;
typedef struct{     //定义一个队列
    Link  front,rear;       //队头和队尾指针
}Q,*Queue;

队列初始化

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
Queue init_queue()
{
    Queue q;
    q=(Queue )malloc(sizeof(Q));
    if(q)
    {
        q->front =NULL;
        q->rear =NULL;
    }
    return q;
}
队列的链式存储_第1张图片
判断队列是否为空
 C++ Code 
1
2
3
4
5
6
7
int empty_quene(Queue q)
{
    if(q && q->front ==NULL && q->rear ==NULL)
        return 1;
    else
        return 0;
}

插入元素
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int in_queue(Queue q,int x)
{
    Link p;
    p=(Link )malloc(sizeof(L ));
    if(p)
    {
        p->data=x;
        p->next =NULL;
        if(empty_quene (q))     //队列为空
            q->front =q->rear =p;
        else
        {
            q->rear ->next =p;
            q->rear =p;
        }
        return 1;
    }
}
队列的链式存储_第2张图片
如图所示,在队列中插入了三个结点之后,队头指针front指向最先插入的结点,尾指针rear指向最后插入的结点。

出队列
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int out_queue(Queue q,int &x)
{
    Link p;
    if(empty_quene (q))
    {
        printf("队列为空");
        return 0;
    }
    x=q->front ->data ;
    p=q->front ;
    q->front =q->front ->next ;
    free(p);
    if(!q->front )
        q->rear =NULL;
    return 1;
}

销毁队列
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void destroy_queue(Queue &q)
{
    Link p;
    if(q)
    {
        while(q->front )
        {
            p=q->front ;
            q->front =q->front ->next ;
            free(p);
        }
    }
    q=NULL;
}

你可能感兴趣的:(C语言,队列,单链表,线性表)