yandihong1 2015-01-18 02:34 采纳率: 100%
浏览 3262
已采纳

c语言循环链表,解决约瑟夫问题

c语言循环链表,一开始用头结点作为开端,创建一连串的节点,到最后一个节点的next指向head的下一个节点可以么。代码如下,虚心求教。
#include
#include
#define N 6
#define M 5
struct people
{
int num;
struct people *next;
};
struct people *head,*last,*p,*history,*now;
int i,j;
int main()
{
head=malloc(sizeof(struct people));
head->num=0;
head->next=NULL;
last=head;
history=head;

for(i=1;i<N+1;i++)
{
    p=malloc(sizeof(struct people));
    p->num=i;
    p->next=NULL;
    last->next=p;
    last=p;
}

history=head;
now=head->next;
while(now!=NULL)
{
    printf("%d",now->num);
    history=now;
    now=now->next;
}

last->next=head->next;

history=last;
now=last->next;
while(now->next!=NULL)
{
    for(j=1;j<M;j++)
    {
        history=now;
        now=now->next;
    }
    p=now->next;
    free(now);
    now=p;
    history->next=now;      
}
printf("%d",now->num);
return 0;   

}

  • 写回答

2条回答 默认 最新

查看更多回答(1条)

报告相同问题?