#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
void printlist(node *head)
{
node *p=NULL;
node *q=NULL;
if(NULL==head)
{
printf("list null\n");
return;
}
q=p=head;
while(p->next!=q)
{
printf("%d ",p->data);
p=p->next;
}
printf("%d ",p->data);
printf("\n");
}
void josephu(node *head)
{
int k=0;
printf("请输入从第几个开始计数:\n");
scanf("%d",&k);
int m=0;
printf("请输入数到几退出:\n");
scanf("%d",&m);
int i=0;
node *p=NULL;
node *q=NULL;
//node *r=NULL;
//r=p=head;
p=head;
printf("head:%d\n",head->data);
for(i=1;i<k;i++)
{
p=p->next;
}
printf("head+k:%d\n",p->data);
while(p->next!=p)
{
for(i=1;i<m;i++)
{
q=p;
p=p->next;
}
printf("出队列的人是%d ",p->data);
q->next=p->next;
free(p);
p=q->next;
}
printf("最后留下的是:%d ",p->data);
printf("\n");
}
int main()
{
node *newnode=NULL;
node *ptr=NULL;
node *head=NULL;
int n=0;
printf("请输入链表的个数:\n");
cin>>n;
int i=0;
head=(node*)malloc(sizeof(node)); //建立链表的头指针
head->data=1;
ptr=head;
for(i=2;i<=n;i++)
{
newnode=(node *)malloc(sizeof(node));
newnode->data=i;
newnode->next=NULL;
ptr->next=newnode;
ptr=newnode;
}
newnode->next=head;
printlist(head);
josephu(head);
return 0;
}
采用循环链表解决围圈问题
最新推荐文章于 2021-10-14 13:09:05 发布