(单循环链表)现在假设有n个人形成一个单向循环链表,求最后剩余的两个节点。

更多资料请点击:我的目录
本篇仅用于记录自己所学知识及应用,代码仍可优化,仅供参考,如果发现有错误的地方,尽管留言于我,谢谢!

据说着名犹太历史学家 Josephus有过以下的故事:在罗马人占领乔塔帕特后,犹太人与Josephus及他的朋友躲到一个洞中,族人决定宁愿死也不要被敌人到,于是决定了一个自杀方式,所有人排成一个圆圈,由第1个人 开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止。
然而Josephus 和他的朋友并不想死,Josephus要他的朋友先假装遵从,他将朋友与自己安排在两个特殊的位置,于是逃过了这场死亡游戏。现在假设有n个人形成一个单向循环链表,求最后剩余的两个节点。

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

struct node//设计节点
{
	int data;
	struct node *next;
};

struct node *creat_list(int data)//创建带头节点的循环链表
{
	struct node *head = malloc(sizeof(struct node));
	head->data = data;	//赋值
	head->next = head;	//自己指向自己
	return head;		//需要返回
}

struct node *new_node(int data)
{
	struct node *new = malloc(sizeof(struct node));
	new->data = data;	//赋值
	new->next = new;	//自己指向自己
	return new;			//需要返回
}


bool itself(struct node * head)//链表为空
{
	return head == head->next;//bool = (head == head->next)? 1 : 0 ;
}

struct node *destory(struct node *head)//销毁链表
{
	struct node *p = head;//定义p指向链表

	while(p->next != head)//找到head的前一个节点
	{
		p = p->next;
	}
	p->next = head->next;//跳过head
	free(head); //释放掉head
	return p->next;//返回head前一个节点
}

void list_link(struct node *head, struct node *new)//在头节点后插入节点
{	
	if(itself(head))//判断是否为空
	{
		head->next = new;//将头节点指向new
		new->next = head;//将new指向头节点
		return;
	}

	struct node *tail = head;//定义tail指向头节点
	while(tail->next != head)//找到头节点前一个节点
	{
		tail = tail->next;
	}
	tail->next = new;//在tail与head节点间插入节点new
	new->next = head;	
}

void show_list(struct node *head)//输出节点元素
{
	
	if(itself(head))
	{
		return;
	}

	struct node *tail = head;
	do
	{		
		printf("%d\t",tail->data);
		tail = tail->next;
	}while(tail != head);
	printf("\n");
}

struct node  *count_three(struct node *head)
{	
	if(itself(head))
		return head;

	while(head != head->next->next)//只要链表节点数大于等于3个,就会一直循环,直至只剩两节点
	{	
		head = destory(head->next->next);
	}
	return head;
}

int main()
{
	struct node *head = creat_list(1);
	printf("请输入将要插入的整数的个数:");
	int n;
	scanf("%d",&n);
	for(int i = 2; i <= n; i++)
	{
		struct node *new = new_node(i);
		if(new == NULL)
		{
			perror("节点内存申请失败");
			exit(0);
		}
		list_link(head, new);
	}
	printf("所有节点元素分别是:\n");
	show_list(head);
	head = count_three(head);

	printf("筛选后的节点元素分别是:\n");
	show_list(head);
	return 0;
}

更多资料请点击:我的目录

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

佳佳鸽

若文章帮到你,能不能请我喝杯茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值