您的位置:首页 > 其它

约瑟夫环问题 链表实现

2011-01-02 16:11 447 查看
#include<stdio.h>
#include<assert.h>
#include<malloc.h>
#define NUM 10
struct node{
int num;
struct node *next;
};
struct node * joy;
struct node * init()
{
struct node *head=(struct node *)(malloc(sizeof(struct node)));
assert(head);
struct node *p=NULL;
struct node *pPre=head;
struct node *pHead=head;
int i;
pPre->next=NULL;
for(i=1;i<NUM;i++)
{
if((p=(struct node *)malloc(sizeof(struct node)))!=NULL)
{
p->num=i;
pPre->next=p;
pPre=p;
}
}
while(pHead)
{
printf("%d/n",pHead->num);
pHead=pHead->next;
}
pPre->next=head;
joy=head;
return head;
}
int main(int argc,char *args[])
{
int start=2;
int overnum=3;
struct node *pCur;
struct node *pPar;
int i;
int j;
//init();
pCur=init();
//printf("%d/n",pCur->num);
for(i=1;i<start;i++)
{
pCur=pCur->next;
}
//printf("%d/n",pCur->num);
while(pCur->next!=pCur)
{
//printf("%d----------/n",pCur->num);
for(j=0;j<overnum;j++)
{
pPar=pCur;
pCur=pCur->next;
}
printf("%d/n",pCur->num);
pPar->next=pCur->next;
free(pCur);
pCur=NULL;
if(pPar!=NULL)
pCur=pPar->next;
}

return 0;
}


起初调试无法输出,发现是初始化链表根本就没连接起来,后来总报double free的错误,把链表的循环从while(pCur!=NULL)改为while(pCur->next!=pCur),错误解决。另外数组实现的话注意两点:1,利用取余循环 2,数组大小每次减1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: