你的问题是出现在函数参数的传递中,因为你是传是指针而你又在函数里改变了指针的指向,那外面的实参却没有改变,所以会说内存不可用(因为你malloc的堆内存的地址是给了函数里面的形参,而main函数中的实参并没有接受到malloc堆的地址)解决问题的办法就把LQUEUE*改成LQUEUE**。逻辑没什么问题,还有C语言中没有引用,那是C++的,别混淆。
修改后的
#include
#include
#include
typedef int ElemType;
typedef struct qnode
{
ElemType data;
struct qnode* next;
}qnode;
typedef struct
{
struct qnode* front;
struct qnode* rear;
}LQUEUE;
void InitQueue(LQUEUE** q)
{
qnode* p = (qnode*)malloc(sizeof(qnode));
if (p == NULL)
exit(-2);
p->next = NULL;
(*q)->rear = p;
(*q)->front = p;
}
void EnQueue(LQUEUE** q, ElemType x)
{
qnode* 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;
}
int main()
{
int n = 0;
int e = 0;
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);
}
while(!Empty(&l))
{
delQueue(&l,e);
printf("%3d",e);
}
printf("\n");
return 0;
}
void main()
{
int n,e;
LQUEUE *l = new LQUEUE;//指针需要申请内存才可以使用
InitQueue(l);
q->front= q->rear=p;
/*
Please input number,end with 0:
12 32 90 -12 33 9 -9 80 19 66 -35 0
12 32 90 -12 33 9 -9 80 19 66 -35
Queue is free!
Press any key to continue
*/
#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);
q->front = q->rear = p;
}
void EnQueue(LQUEUE *q,ElemType x) {
q->rear->data = x;
q->rear->next = (qnode *)malloc(sizeof(qnode));
q->rear = q->rear->next;
}
int Empty(LQUEUE *q) {
if(q->front == q->rear) return 1;
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;
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");
while(1) {
scanf("%d",&n);
if(n == 0) break;
EnQueue(L,n);
}
while(delQueue(L,&e)) printf("%d ",e);
printf("\n");
}