#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct qnode{
ElemType data;
struct qnode *next;
}qnode;
typedef struct {
qnode *front;
qnode *rear;
}LQUEUE;
void InitQueue(LQUEUE * &q)
{ qnode *p;
p=(qnode *)malloc(sizeof(qnode));
if(!p) exit(-2);
p->next=0;
q->front= q->rear=p;
}
void EnQueue(LQUEUE *q,ElemType x)
{ qnode *s;
s=(qnode *)malloc(sizeof(qnode));
s->data=x;s->next=NULL;
if (q->front==NULL&&q->rear==NULL)
{q->rear=q->front=s;}
else
q->rear->next=s; q->rear=s;
}
int Empty(LQUEUE *q)
{if (q->front==NULL&&q->rear==NULL)
return 1 ;
else
return 0;
}
int delQueue(LQUEUE *q,ElemType &x)
{ qnode *p;
if(Empty(q)){
printf("\n Queue is free!");
return 0;}
p=q->front;
x=p->data;
if(q->rear==q->front)
q->rear=q->front=NULL;
free(p);
return 1;
}
void main()
{
int n,e;
LQUEUE *l;
InitQueue(l);
printf("Please input number,end with 0:\n");
scanf("%d",&n);
while(n==0)
{
EnQueue(l,n);
}
while(!Empty(l))
{
delQueue(l,e);
printf("%3d",e);
}
printf("\n");
}
编译没有问题,就是生成exe执行文件时,系统报错说内存不可写什么的!求大神指教啊
你的问题是出现在函数参数的传递中,因为你是传是指针而你又在函数里改变了指针的指向,那外面的实参却没有改变,所以会说内存不可用(因为你malloc的堆内存的地址是给了函数里面的形参,而main函数中的实参并没有接受到malloc堆的地址)解决问题的办法就把LQUEUE*改成LQUEUE**。逻辑没什么问题,还有C语言中没有引用,那是C++的,别混淆。
修改后的
#include<stdio.h>G:\数据结构\实验\queue.cpp(60) : error C2664: 'InitQueue' : cannot convert parameter 1 from 'LQUEUE ** ' to 'LQUEUE *& '
A reference that is not to 'const' cannot be bound to a non-lvalue
像你说的那样出现的编译问题
用指针也可以,但千万别在函数里面修改q的指向就行可以
scanf("%d", &an);那为什么程序出来,结果是混乱的数字?没有达到理想效果
追答错误挺多的,简单改了一下,可以了。
#include
#include
#include
typedef int ElemType;
typedef struct qnode{
ElemType data;
struct qnode *next;
}qnode;
typedef struct {
qnode *front;
qnode *rear;
}LQUEUE;
void InitQueue(LQUEUE * &q)
{
// qnode *p;
// p=(qnode *)malloc(sizeof(qnode));
// if(!p) exit(-2);
// p->next=0;
q->front= q->rear=NULL;
}
void EnQueue(LQUEUE *q,ElemType x)
{ qnode *s;
s=(qnode *)malloc(sizeof(qnode));
s->data=x;s->next=NULL;
if (q->front==NULL&&q->rear==NULL)
{q->rear=q->front=s;}
else
q->rear->next=s; q->rear=s;
}
int Empty(LQUEUE *q)
{if (q->front==NULL&&q->rear==NULL)
return 1 ;
else
return 0;
}
int delQueue(LQUEUE *q,ElemType &x)
{ qnode *p;
if(Empty(q)){
printf("\n Queue is free!");
return 0;}
p=q->front;
x=p->data;
if(q->rear==q->front)
q->rear=q->front=NULL;
else
q->front = p->next;
free(p);
return 1;
}
void main()
{
int n,e;
LQUEUE *l = (LQUEUE *)malloc(sizeof(LQUEUE));
InitQueue(l);
printf("Please input number,end with 0:\n");
scanf("%d",&n);
while(n!=0)
{
EnQueue(l,n);
scanf("%d",&n);
}
while(!Empty(l))
{
delQueue(l,e);
printf("%3d",e);
}
printf("\n");
}
好像改了要出错吧
追答q的指向不能直接被修改啊