链表:
#include<stdio.h>
#include<malloc.h>
typedef struct node{
int info;
struct node *next;
};
node *tbuildhlink(int n) /*带头节点的尾插法*/
{
node *head,*s,*p2;
int i=1;
head=(node *)malloc(sizeof(node));
p2=head;
while(i<=n)
{
s=(node *)malloc(sizeof(node));
s->info=i;
p2->next=s;
p2=s;
i++;
}
if(p2) p2->next=head;
return(head);
}
void Display(struct node* head)
{
node *p;
p=head->next;
if(!p)
{
printf("\nthe hlink is empty!");
}
else
{
printf("\nthe value of the hlink is:\n");
while(p!=head)
{
printf("%d--->",p->info);
p=p->next;
}
}
printf("^\n");
}
int delete_node(struct node *head,int n,int m)
{
int count=1,sum=n;
struct node *p,*pre;
pre=head;
p=pre->next;
while(sum>1)
{
if(p==head)
{
p=p->next;
}
if(count<m)
{
pre=p;
p=p->next;
count++;
}
if(count==m)
{
if(p==head)
{
p=p->next;
}
printf("第%d个人出列.\n",p->info);
pre->next=p->next;
free(p);
p=pre->next;
count=1;
sum--;
}
}
return(pre->info);
}
int main()
{
node *head;
int n,m;
printf("输入n,m:");
scanf("%d%d",&n,&m);
head=tbuildhlink(n);
Display(head);
printf("最后剩下第%d个.\n",delete_node(head,n,m));
return(0);
}