数据结构——链队列的基本算法

代码主要来源:【数据结构】【清华大学】【严蔚敏】

关于栈和队列的基本操作概括起来主要的内容有以下八种:
构造、销毁
置空、判空
取头、求长
输入、输出

下面的代码包括了基本八种外加一个
Status QueueTraverse(LinkQueue Q,void(*vi)(QElemType))函数

//++++++++++++++++++++ 链队列 ++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <stdio.h>
#include <stdlib.h> 
#define OK 1 
#define ERROR 0
#define OVERFLOW -1
#define TRUE 1
#define FALSE 0
typedef int QElemType;
typedef int Status;

typedef struct QNode
{
    QElemType 			data;
    struct QNode		*next;
} QNode, *QueuePtr;

struct LinkQueue
{
    QueuePtr front,rear; 	// 队头、队尾指针
};

Status InitQueue(LinkQueue &Q)
{
    // 构造一个空队列Q
    if(!(Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode))))
        exit(OVERFLOW);
    Q.front->next=NULL;
    return OK;
}

Status DestroyQueue(LinkQueue &Q)
{
    // 销毁队列Q(无论空否均可)
    while(Q.front)
    {
        Q.rear=Q.front->next;
        free(Q.front);
        Q.front=Q.rear;
    }
    return OK;
}

Status ClearQueue(LinkQueue &Q)
{
    // 将Q清为空队列
    QueuePtr p,q;
    Q.rear=Q.front;
    p=Q.front->next;
    Q.front->next=NULL;
    while(p)
    {
        q=p;
        p=p->next;
        free(q);
    }
    return OK;
}

Status QueueEmpty(LinkQueue Q)
{
    // 若Q为空队列,则返回TRUE,否则返回FALSE
    if(Q.front==Q.rear)
        return TRUE;
    else
        return FALSE;
}

int QueueLength(LinkQueue Q)
{
    // 求队列的长度
    int i=0;
    QueuePtr p;
    p=Q.front;
    while(Q.rear!=p)
    {
        i++;
        p=p->next;
    }
    return i;
}

Status GetHead(LinkQueue Q,QElemType &e)
{
    // 若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR
    QueuePtr p;
    if(Q.front==Q.rear)
        return ERROR;
    p=Q.front->next;
    e=p->data;
    return OK;
}

Status EnQueue(LinkQueue &Q,QElemType e)
{
    // 插入元素e为Q的新的队尾元素
    QueuePtr p;
    if(!(p=(QueuePtr)malloc(sizeof(QNode)))) // 存储分配失败
        exit(OVERFLOW);
    p->data=e;
    p->next=NULL;
    Q.rear->next=p;
    Q.rear=p;
    return OK;
}

Status DeQueue(LinkQueue &Q,QElemType &e)
{
    // 若队列不空,删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR
    QueuePtr 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;
}

Status QueueTraverse(LinkQueue Q,void(*vi)(QElemType))
{
    // 从队头到队尾依次对队列Q中每个元素调用函数vi()。一旦vi失败,则操作失败
    QueuePtr p;
    p=Q.front->next;
    while(p)
    {
        vi(p->data);
        p=p->next;
    }
    printf("\n");
    return OK;
}

int main()
{
	
}

猜你喜欢

转载自blog.csdn.net/qq_41856733/article/details/83963462
今日推荐