读书人

关于队列的有关问题,大家帮忙看下

发布时间: 2012-02-14 19:19:19 作者: rapoo

关于队列的问题,大家帮忙看下.
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 10

typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int front, rear;
}Queue;


/* 构造一个空环行队列 */
void InitQueue(Queue qu)
{
qu.rear = qu.front = 0;
}
/* 将元素x入队 */
void EnQueue(Queue qu, ElemType x)
{
qu.data[qu.rear] = x;
qu.rear = (qu.rear+1)%MAXSIZE;
}
/* 打印建立的队列 */
void Print(Queue qu)
{
int i;
for (i=qu.front; i <qu.rear; i++)
printf( "%d ", qu.data[i]);
printf( "\n ");
}

int main()
{
Queue qu;
ElemType x;

InitQueue(qu);
printf( "Please input elem end with 0\n ");
scanf( "%d ", &x);
while ( x != 0)
{
EnQueue(qu,x);
scanf( "%d ", &x);
}
Print(qu);

system( "pause ");
return 0;
}

没输出我输进的数.
编译时警告:主函数qu没初始化,请问这里qu要怎么初始化,InitQueue(qu);不就是初始化了么?谢谢!


[解决办法]
你这里
qu.rear = qu.front = 0;
qu.data[qu.rear] = x;
qu.rear = (qu.rear+1)%MAXSIZE;
都是局部变量,生命期是随着函数的返回就销毁了。如果一定要用顺序方式来做,全部写在主函数里得了。。。
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 10

typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int front, rear;
}Queue;

int main()
{
Queue qu;
ElemType x;
int i;
for (i = 0; i <MAXSIZE; i++)
qu.data[i] = 0;


qu.rear = qu.front = 0;
printf( "Please input elem end with 0\n ");
scanf( "%d ", &x);
while ( x != 0)
{
qu.data[qu.rear] = x;
qu.rear = (qu.rear+1)%MAXSIZE;
scanf( "%d ", &x);
}
for (i=qu.front; i <qu.rear; i++)
printf( "%-2d ", qu.data[i]);
printf( "\n ");

system( "pause ");
return 0;
}

读书人网 >C语言

热点推荐