围圈报数-单项循环链表

这道题,说难不难,说简单也不简单,本菜鸟,,,,,哎,,,,

下面是更正后的代码:

//创建一个单向循环链表
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
	int id;
	struct node * next;
}node;
//单向循环链表的长度 
int len(node *L)
{
	int n=1;
	node *p=L;
	while(p->next!=L){
		n++;
		p=p->next;
	}
	return n;
}
//找到L的前驱(游戏开始前就应该找到前驱,因为L也会被删掉),,,,,,这里是为了以后找到要删除节点的前驱节点
node * find(node *L)
{
	node *p=L;
	while(p->next!=L)
		p=p->next;
	return p;
} 

//创建单向循环链表并删除相应的节点 
void print_List(int n)
{
	//创建不带头节点的循环单链表 
	node *L=(node *)malloc(sizeof(node));
	L->id=1;
	L->next=L;
	node *tail=L;
	int i;
	for(i=2;i<=n;i++)
	{
		node * temp=(node *)malloc(sizeof(node));
		temp->id=i;
		temp->next=L;
		tail->next=temp;
		tail=temp;
	}		
	//开始围圈并删除序号为3的节dian
	node * p=L; 
	node * p_pre=find(L);
	while(p!=NULL)//链表不空的时候 
	{ 
		if(len(p)==1)//删除到最后只剩下一个节点的时候 
		{
			printf("%d\n",p->id); 
			break;
		}
		//剩下不止一个节点的时候 
		int i;
		for(i=1;i<3;i++){p_pre=p_pre->next;p=p->next;}//找到要删除的节点p  
		printf("%d ",p->id);//输出 
		node *t=p;
		p_pre->next=t->next;
		p=t->next;
		free(t);//删除节点  
	} 	
}
int main()
{
	int m,i;
	scanf("%d",&m);
	int n;
	for(i=0;i<m;i++)
	{
		scanf("%d",&n);
		print_List(n);	
	}
	return 0;	
} 
发布了6 篇原创文章 · 获赞 2 · 访问量 296

猜你喜欢

转载自blog.csdn.net/qq_38549584/article/details/104829243