找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 4382|回复: 0
打印 上一主题 下一主题
收起左侧

C语言:约瑟夫环问题(源代码)

[复制链接]
跳转到指定楼层
楼主
ID:86860 发表于 2015-7-26 00:46 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 geige 于 2015-7-26 00:48 编辑


#include<stdio.h>
#include<stdlib.h>

struct stu //构建一个新的数据类型
{
int num;

struct stu *next;

};

struct stu *createlist(int n);  //函数声明
int main()
{
struct stu *head,*p,*temp;   //定义头指针,以及中间指针temp,用来删除节点

int n,m,i,j=1,flag=0;

printf("Please input n and m:\n");
scanf("%d%d",&n,&m);

head=createlist(n);          //调用函数来创建链表并返回头指针赋值给head


p=head->next;                //将首节点的地址赋值给p

if(m==1)                     //如果m等于1,直接按顺序输出
{
while(p!=NULL)
{
printf("%d ",p->num);
p=p->next;
}

putchar('\n');
}

else
{

while(n!=1)
{
for(i=1;i<=n;i++)
{
if(p!=NULL)
{
if(j==m)
{
printf("%d ",p->num);

if(p==head->next)
head->next=p->next; //如果删除的是首结点,那么将第二个节点作为首节点
temp->next=p->next;
p=temp->next;
j=1;
flag++;
}
else
{
j++;
temp=p;
p=p->next;
}
}
}

n=n-flag; //退出的人数要减去
flag=0;
p=head->next; //将首节点重新赋给p
}

printf("%d\n",temp->num); //输出最后一个数
}

free(p); //释放内存

    return 0;

}


struct stu *createlist(int n)
{
int i;

struct stu *phead=(struct stu*)malloc(sizeof(struct stu)),*ptail;  //申请头结点

if(phead==NULL)
{
printf("Not able apply for memory !\n");

return 0;
}

ptail=phead; //
ptail->next=NULL; //将头结点的下一个地址置空

for(i=1;i<=n;i++)
{
struct stu *pnew=(struct stu*)malloc(sizeof(struct stu)); //开辟新的节点

if(pnew==NULL)
{
printf("Not able apply for memory !\n");

return 0;
}

pnew->num=i;
ptail->next=pnew;
pnew->next=NULL;
ptail=pnew; //节点前移
}
return phead; //返回头指针


}


分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享淘帖 顶 踩
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表