米兰的小铁匠z 2019-10-07 20:57 采纳率: 25%
浏览 260
已采纳

循环链表的顺序实现出现一个问题(抛异常)

循环链表的顺序实现出现一个问题

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define FALSE 0
#define MAX_SIZE 8

typedef int QElemType;
typedef int Status;
struct  SqQueue
{
    QElemType* base;
    int front;
    int rear;
};

void InitQueue(SqQueue& Q){
    if (!(Q.base = (QElemType*)malloc(sizeof(SqQueue))))
        exit(0);
    Q.front = Q.rear = 0;
}

void DestroyQueue(SqQueue& Q){
    if (Q.base)
    {
        free(Q.base);
    }
    Q.base = NULL;
    Q.front = Q.rear = 0;
}

void ClearQueue(SqQueue& Q){
    Q.front = Q.rear = 0;
}

Status QueueEmpty(SqQueue& Q){
    if (Q.rear == Q.front)
    {
        return 1;
    }
    return 0;
}

Status QueueLength(SqQueue& Q){
    return (Q.rear - Q.front + MAX_SIZE) % MAX_SIZE;

}

Status GetHead(SqQueue& Q, QElemType& e){
    if (Q.rear == Q.front)
    {
        return FALSE;
    }
    return e = Q.base[Q.front];
}
void Visit(QElemType e){
    printf("%d ",e);
}

Status EnQueue(SqQueue& Q, QElemType e ){
    if ((Q.rear + 1) % MAX_SIZE == Q.front)
        return FALSE;
    Q.base[Q.rear] = e;
    Q.rear = (Q.rear + 1) % MAX_SIZE;
    return OK;
}

Status DeQueue(SqQueue& Q, QElemType& e){
    if (Q.rear == Q.front)
        return 0;
    e = Q.base[Q.front];
    Q.front = (Q.front + 1) % MAX_SIZE;
    return 1;
}

Status QueueTraverse(SqQueue& Q){
    int i;
    i = Q.front;

    while (i != Q.rear)
    {
        Visit(Q.base[i]);
        i = (i+1)%MAX_SIZE;
    }
    printf("\n");
    return OK;
}
int main(){
    SqQueue Q;
    QElemType E = 0;
    InitQueue(Q);

    for (int i = 5; i < 20; i++)
        EnQueue(Q, i);

    printf("%d \n ", QueueEmpty(Q));

    DeQueue(Q, E);
    printf("出队:%d \n",E);

    QueueTraverse(Q);

    printf("长度:%d\n", QueueLength(Q));

    ClearQueue(Q);
    printf("清空后长度:%d\n", QueueLength(Q));

    DestroyQueue(Q);
    printf("\n");
    return 0;
}

图片说明
图片说明
想问为什么会抛出异常
free那个函数明明有内存直向一块内存,释放不掉会是什么原因?

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-10-07 21:25
    关注

    if (!(Q.base = (QElemType*)malloc(sizeof(SqQueue))))
    这里,你既然是数组,应该是
    if (!(Q.base = (QElemType*)malloc(sizeof(QElemType) *MAX_SIZE));
    否则后面你的操作都越界了。

    你根本就没有链表,是顺序表哦。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)