线性表练习1——约瑟夫环

问题描述

在这里插入图片描述

解题思路

  • 涉及循环链表的创建,删除

代码

#include <iostream>
using namespace std;
typedef int ElemType;

typedef struct CNode
{
	struct CNode* next;
	ElemType id;
	ElemType psd;
}CNode,*CLinkList;
bool CreateCLinkList(CLinkList& L, int n)
{
	L = (CNode*)malloc(sizeof(CNode));
	cin >> L->psd;
	L->id = 1;
	CNode* head = L;
	for (int i = 1; i < n; i++)
	{
		CNode* newNode = (CNode*)malloc(sizeof(CNode));
		cin >> newNode->psd;
		newNode->id = i + 1;
		L->next = newNode;
		L = newNode;
	}
	L->next = head;
	L = head;
	return true;
}
int main()
{
	int n, m;
	cin >> n >> m;
	CLinkList JosephList;
	CreateCLinkList(JosephList, n);
	CNode* p = JosephList;
	while (JosephList)
	{
		for (int i = 0; i < m-2; ++i)
		{
			p = p->next;
		}
		cout << p->next->id<<" ";
		m = p->next->psd;
		CNode* q = p->next;
		if (q->next == p)
		{
			cout << p->id;
			break;
		}
		p->next = q->next;
		free(q);
		if (m == 1)
		{
			CNode* q2 = p->next;
			cout << q2->id<<" ";
			if (q2->next = p)
			{
				cout << p->id;
				break;
			}
			p->next = q2->next;
			free(q2);
		}
		p = p->next;
	}
	return 0;
}
发布了33 篇原创文章 · 获赞 3 · 访问量 602

猜你喜欢

转载自blog.csdn.net/qq_43647628/article/details/104681391