|
本帖最后由 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; //返回头指针
}
|
|