读书人

懂得用C语言实现数据结构的近来啊帮个

发布时间: 2012-02-17 17:50:41 作者: rapoo

懂得用C语言实现数据结构的近来啊,帮个忙!!!队列问题
#include <stdio.h>
#include <malloc.h>
#include <conio.h>


typedef int Status;
typedef int QElemType;


#define NULL 0
#define OVERFLOW -2
#define OK 1
#define ERROR 0


typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;

typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;

Status InitQueue(LinkQueue *Q)/*队列生成*/
{Q-> front=Q-> rear=(QueuePtr)malloc(sizeof(QNode));
if(!Q-> front)exit(OVERFLOW);
Q-> front-> next=NULL;
return OK;
}


Status EnQueue(LinkQueue *Q,QElemType e)/*向队列输入元素*/
{
QueuePtr p;
p=(QueuePtr)malloc(sizeof(QNode));
if(!p)exit(OVERFLOW);
p-> data=e;p-> next=NULL;
Q-> rear-> next=p;
Q-> rear=p;
return OK;
}


void main()
{int i,n;
LinkQueue *Q;
QElemType e;
QueuePtr p;
InitQueue(Q);

printf( "\ninput QElem please!e= ");
scanf( "%d ",&e);

EnQueue(Q,e);
printf( "Now you have insert a QElem,that is %d ",p-> data);
}


我是用C语言在TC2.0上实现的,但出现了错误


[解决办法]
Status InitQueue(LinkQueue *Q)/*队列生成*/
{Q-> front=Q-> rear=(QueuePtr)malloc(sizeof(QNode));
if(!Q-> front)exit(OVERFLOW);
Q-> front-> next=NULL;
return OK;
}

在这个函数里面的Q,
与在main函数那里的
LinkQueue *Q;
QElemType e;
QueuePtr p;
InitQueue(Q);
出了问题.

因为你在main里面的LinkQueue *Q只是一个指针,而没有空间.你希望在InitQueue函数里对Q进行申请空间操作,那么最简单的改法是把你的

Status InitQueue(LinkQueue *Q)/*队列生成*/
改为
Status InitQueue(LinkQueue *&Q)/*队列生成*/

指针的引用,这样在函数InitQueue里的指针Q就相当于main那里的Q,对它进行的操作都可以带回到main函数那边

读书人网 >C语言

热点推荐