加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

第三章 队列【数据结构】【链队列】

发布时间:2020-12-15 06:34:08 所属栏目:安全 来源:网络整理
导读:最近越来越感觉到c语言指针的强大~~ #includestdio.h #include stdlib.h #define QElemType int #define OK 1 #define ERROR 0 #define OVERFLOW 0 typedef int Status; // ------------单链表------------队列的链式存储结构 typedef struct QNode { QElemT

最近越来越感觉到c语言指针的强大~~

#include<stdio.h>
#include<stdlib.h>
#define QElemType int
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef int Status;
//------------单链表------------队列的链式存储结构 
typedef struct QNode {
    QElemType data;
    struct QNode *next;
}QNode,*QueuePtr;

typedef struct{
    QueuePtr front,rear;队头指针和队尾指针 
}LinkQueue;
-----------------基本函数操作----------------- 
Status InitQueue(LinkQueue &Q,int n)
{
    Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));构造一个空队列 
    if(!Q.front)
        exit(OVERFLOW);
    Q.front->next = NULL;
    printf("请输入n个数n");
    for(int i = 1; i <= n; i ++)读入n个数,并依次加入队列 
    {
        QueuePtr p = (QueuePtr)sizeof(QNode));
        scanf(%d",&p->data);
        p->next = NULL;
        Q.rear->next = p;
        Q.rear = p;
    }
    return OK;
}
销毁队列Q 
Status DestroyQueue(LinkQueue &Q)
{
    while(Q.front)
    {
        Q.rear = Q.front->next ;
        free(Q.front);
        Q.front = Q.rear ;
    }
    插入元素e为Q 的新的队尾元素 
Status EnQueue(LinkQueue &Q,QElemType &e)
{
    QueuePtr p = (QueuePtr)sizeof(QNode));
    if(!p)
        exit(OVERFLOW);存储分配失败 
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    若队列不为空,则删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR 
Status DeQueue(LinkQueue &Q,QElemType &e)
{
    if(Q.front == Q.rear )
        return ERROR;
    QueuePtr p = (QueuePtr)sizeof(QNode));
    p = Q.front->next ;
    e = p->data ;
    Q.front->next = p->next ;
    free(p);
    return OK;
}

void PrintQueue(LinkQueue *Q)输出队列Q 中的元素 
{
    QueuePtr p = Q->front->next ;将队列的头元素指针地址赋值给p 
    while(p!=NULL)
    {
        printf(%d n");
}
int main() 
{
    LinkQueue Q;
    int n;
    printf(请输入nn");
    
    scanf(读入n个数,加入队列 
    InitQueue(Q,n);初始化队列 
    printf(初始化后的队列为:n");
    PrintQueue(&Q);输出队列中的元素 
    
    int e;
    printf(请输入一个整数en");
    scanf(读入e 
    EnQueue(Q,e);插入元素e为Q的新的队尾元素 
    printf(将e插入队尾后,队列更新为n输出插入队尾后队列的值 
    
    DeQueue(Q,e);删除Q的队头元素,用e返回其值 
    printf(删除队头元素后的队列为n输出删除队头后的队列 
    
    DestroyQueue(Q);销毁队列,释放存储空间 
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读