为什么输出错误了?

Corrine_CLX 2012-10-16 06:12:41
我构造了一个循环单向链表,想实现约瑟夫环问题。为什么在打印输出的时候错误 呢?请大神们帮忙看看,感激不尽!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>

#define MAX 100
#define MIN 80
#define AMOUNT 5
#define LOOP 7


struct node
{
int num;
node* link;
};
bool CreateLoopList(node* head,int amount);
void PrintList(node* head,int amount);
void JosephPrintList(node* head, int amount, int loop);

int main()
{
node* head = (node*)malloc(sizeof(node));
head->link = NULL;
CreateLoopList(head,AMOUNT);
PrintList(head,AMOUNT);
JosephPrintList(head,AMOUNT,LOOP);
return 0;
}

bool CreateLoopList(node* head,int amount)
{
bool flag = true;
node* tail = head;

srand((unsigned int)time(NULL));
for(int i = 0; i < amount-1; i++) //第一次赋值了两个节点
{
if(head->link == NULL)
{
head->num = rand()%((MAX+1)-MIN)+MIN;
}
node* newNode = (node*)malloc(sizeof(node));
if(newNode == NULL) //内存分配不成功
{
flag = false;
break;
}
newNode->num = rand()%((MAX+1)-MIN)+MIN;
newNode->link = NULL;

tail->link = newNode;
tail = newNode;
}
tail->link = head; //构成循环
return flag;
}

void PrintList(node* head,int amount)
{
node* tail = head;
int count = amount;
while(tail != NULL && count != 0)
{
printf("%d ", tail->num);
tail = tail->link;
count--;
}
printf("\n");
}

void JosephPrintList(node* head, int amount, int loop)
{
int i,k;
/* for(i=0; i<amount; i++)
{
k=(i+DISTANCE)%10;
printf("%c ", array[k]);
}
*/
node* p=head;
for(i = 0; i < amount; i++)
{
k = (i+loop)%amount;
printf("%d ", (p+k)->num);
}

printf("\n");
}

...全文
92 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xpingping 2012-10-16
  • 打赏
  • 举报
回复
void JosephPrintList(node* head, int amount, int loop)
{
int flag = 1;
node* tmp = head;
node* p=head;

while(amount!=0)
{
if(flag == loop -1)
{
printf("%d ",tmp->link->num);
tmp = tmp->link->link;
flag = 1;
amount --;
}
else
{
flag ++;
tmp = tmp->link;
}
}
printf("\n");
}

首先你没有理解约瑟夫环的环,
其次你环形列表的内存空间不是连续的
通过指针偏移来取值是不对的。
夏天__ 2012-10-16
  • 打赏
  • 举报
回复
程序本身没有语法错误,自己单步调试一下吧,

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧