为什么这个程序在gcc中能够编译通过,而VC6.0中编译后无法运行

下面是用队列法求解约瑟夫问题的代码
http://zhidao.baidu.com/question/340700604.html

那个程序本身有几个问题。
1. 在main()中没调用InitQueue(q)
2. 在main()中没释放分配的q。
3. 在DeQueue()中不应该分配QueueNode,且释放出队的QueueNode也释放得不对。
能运行是靠“运气”

下面是改后的程序,正确运行。楼主对照看看加了“////”的那4行。
#include<stdio.h>
#include<stdlib.h>
//循环队列
//typedef int ElemType;
typedef struct QueueNode
{
int data;
struct QueueNode *next;
}QueueNode;
typedef struct Queue
{
QueueNode *front;
QueueNode *rear;
}Queue;

void InitQueue(Queue *q)
{
q->front=q->rear=NULL;
}

void EnQueue(Queue *q , int value)
{
QueueNode *temp=(QueueNode*)malloc(sizeof(QueueNode));
temp->data=value;
if(q->rear==NULL)
{
temp->next=temp;
q->rear=q->front=temp;
}
else
{
temp->next=q->rear->next;
q->rear->next=temp;
q->rear=temp;
}
}//enter a element from the tail

void DeQueue(Queue *q, int *value)
{
QueueNode *temp;////

if(q->rear==NULL)
{
return;
}// It's null
else if(q->rear->next==q->rear)
{
*value=q->front->data;
free(q->rear);
q->rear=q->front=NULL;
}//It just has one node
else
{
*value=q->front->data;
temp=q->front;
q->front=temp->next;
q->rear->next=q->front;
free(temp);////
}//more one node
}//delete a element from the head
/*问题定义:设有n个人围坐在圆桌周围,从某个位置开始编号1、2、3、…、n。编号为1的人开始从1报数,数到m的人便出列,下一个人(第m+1个人)又从1开始报数,
数到m的人便出列,……,如此重复,直到最后一个人出列为止。试对任意输入的n、m,求出列顺序。*/
int main()
{
Queue *q=(Queue*)malloc(sizeof(Queue));
int i,m,n,count,temp;
printf("请输入人数n和循环要报的数m(两数之间留个空格)\n");
scanf("%d%d",&n,&m);
InitQueue(q);////
for(i=1;i<=n;i++)
EnQueue(q,i);
printf("出圈序列:\n");
while(q->front)
{ count=1;
while(count<m)
{
q->front=q->front->next;
q->rear=q->rear->next;
count++;
}
count=1;
DeQueue(q,&temp);
printf("%d ",temp);
}
free(q);////
putchar('\n');
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网