数据结构与算法之链表(四) 约瑟夫环

在一些大的公司尤其是大的互联网公司面试的时候,链表的一些趣味算法是经常出现。

下面就来是两个常见的面试题:

1.判断一个单链表是不是存在环。


#include<iostream>
using namespace std;

struct node
{
	int element;
	node *next;
};

//创建单链表链表
node *create_list(int n)
{
	if(n <= 0)
	{
		return  NULL;
	}
	
	node *head = NULL;
	node *p = new node;
	if(p == NULL)
	{
		return NULL;
	}
	head = p;
	while(--n)
	{
		node *q = new node;
		if(q == NULL)
		{
			return NULL;
		}
		p->next = q;
		p = q;
	}
	p->next = NULL;

	return head;
}


//创建循环单链表链表
node *create_loop_list(int n)
{
	if(n <= 0)
	{
		return  NULL;
	}
	
	node *head = NULL;
	node *p = new node;
	if(p == NULL)
	{
		return NULL;
	}
	head = p;
	while(--n)
	{
		node *q = new node;
		if(q == NULL)
		{
			return NULL;
		}
		p->next = q;
		p = q;
	}
	p->next = head;

	return head;
}


bool has_roll(const node* head)
{
	const node* p = head;
	const node* q = head->next;
	while(q != NULL && q->next != NULL && p != q)
	{
		p = p->next;
		q = q->next->next;
	}

	if(p == q)
	{
		return  true;
	}
	else
	{
		return false;
	}
}

int main()
{
	int n = 0;
	cin>>n;
	node *head = create_list(n);
	if(has_roll(head))
	{
		cout<<"有环"<<endl;
	}
	else
	{
		cout<<"无环"<<endl;
	}

	head = create_loop_list(n);
	if(has_roll(head))
	{
		cout<<"有环"<<endl;
	}
	else
	{
		cout<<"无环"<<endl;
	}



	return 0;
}

2.有N个小孩围成一圈,从第K个儿童从1开始依次报数,直到数到M,数到M的同学出列,下一个同学再从1开始报数到M,依次循环,直到最后剩下一个同学,问最后一个同学是谁。

#include<iostream>
using namespace std;

struct node
{
	int num;
	node *next;
};

//创建循环单链表链表
node *create_loop_list(int n)
{
	if(n <= 0)
	{
		return  NULL;
	}
	
	node *head = NULL;
	node *p = new node;
	if(p == NULL)
	{
		return NULL;
	}
	head = p;
	int i = 1;
	p->num = i;
	while(--n)
	{
		node *q = new node;
		q->num = ++i;
		if(q == NULL)
		{
			return NULL;
		}
		p->next = q;
		p = q;
	}
	p->next = head;

	return head;
}

//删除从头结点起的第m个结点
node *delete_node(node* head, int m)
{
	node *p = head;
	node *t = p;
	m = m - 1;
	while(m--)
	{
		t = p;
		p = p->next;
	}

	t->next = p->next;
	head = t->next;
	delete p;

	return head;

}


node *last_one(int N, int K, int M)
{
	node *head = create_loop_list(N);

	while(--K)
	{
		head = head->next;
	}

	
	while(head != head->next)
	{
		head = delete_node(head, M);
	}
	
	return head;
	
}


int main()
{
	int N = 0;
	int K = 0;
	int M = 0;
	cin>>N>>K>>M;
	node *last = last_one(N, K, M);
	cout<<last->num<<endl;


	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值