和乐i 2020-08-03 18:49 采纳率: 100%
浏览 296
已采纳

求助大神,c语言malloc内存分配失败,为什么

“头节点申请成功”未打印,请大神看一下怎么回事

#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;

//链队列
typedef int datatype;
typedef struct Node{
    datatype data;
    struct Node *next; 
}linklist;

typedef struct{
    linklist *front,*rear;
}linkqueue; 

//置空队
linkqueue *SetNullQ(linkqueue *q)
{
    q->front=(linklist*)malloc(sizeof(linklist));   //申请头节点
    cout<<"头节点申请成功"<<endl; 
    q->front->next=NULL;
    q->rear=q->front;
    cout<<"置空队列成功"<<endl; 
    return q; 
} 

//判队空
int EmptyQ(linkqueue *q)
{
    if(q->front==q->rear)
        return 1;
    else
        return 0;
} 

//取队头节点数据
datatype *FrontQ(linkqueue *q)
{
    datatype *ret;
    if(EmptyQ(q)){
        cout<<"queue is empty"<<endl;
        return NULL;
    }
    else{
        ret=(datatype*)malloc(sizeof(datatype));
        *ret=q->front->next->data;
        return ret;
    }
}

//入队
void EnQueueQ(linkqueue *q,datatype x)
{
    q->rear->next=(linklist*)malloc(sizeof(linklist));
    q->rear=q->rear->next;
    q->rear->data=x;
    q->rear->next=NULL;
    cout<<x<<"已入队"<<endl; 
} 

//出队,返回被删除节点的值 
datatype *DeQueueQ(linkqueue *q)
{
    datatype *ret;
    linklist *s;
    if(EmptyQ(q)){
        cout<<"queue is empty"<<endl;
        return NULL;
    }
    else{
        s=q->front->next;
        if(s->next==NULL)
        {
            q->front->next=NULL;
            q->rear=q->front;
        }
        else q->front->next=s->next;
        ret=(datatype*)malloc(sizeof(datatype));
        *ret=s->data;
        return ret;
    }
} 

int main()
{
    linkqueue *q=NULL;
    cout<<"置空队列"<<endl; 
    SetNullQ(q);
    datatype x;
    cout<<"请输入要入队的元素,以#结束:"<<endl; 
    while((x=getche())!='#')
    {
        EnQueueQ(q,x);
    }
    cout<<"取队头元素"<<endl; 
    datatype *a=FrontQ(q);
    cout<<"队头元素为"<<*a<<endl;
    cout<<"出队,返回被删除节点的值 "<<endl;
    datatype *b=DeQueueQ(q);
    cout<<"节点"<<*b<<"已被删除"<<endl;
    cout<<"出队,返回被删除节点的值 "<<endl;
    datatype *c=DeQueueQ(q);
    cout<<"节点"<<*c<<"已被删除"<<endl;
    return 0;
}
  • 写回答

2条回答 默认 最新

  • 旺旺^淞 2020-08-03 19:25
    关注

    既然是C++,你可以用new函数,没有那么繁琐。p->front = p->rear = new listqueue.我做了一些复习资料,你可以康康

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改