约瑟夫环问题循环链表实现

循环链表实际上是单向链表的最后一个结点的指针指向头结点,其他并无差别。

#include
#include

using namespace std;

typedef struct listnode{
	int data;
	listnode * next;
};

listnode * creat_circularlist(int cycle){
	listnode *head, *p, *s;
	int x;
	head = (listnode *)malloc(sizeof(listnode));
	p = head;
	while (cycle)
	{
		cout << "请输入一个值" << endl;
		cin >> x;
		s = (listnode *)malloc(sizeof(listnode));
		s->data= x;
		p->next = s;
		p = s;
		--cycle;
	}
	head = head->next;
	p->next = head;
	return head;
}

listnode * deletenode(listnode * head , int startindex, int deleteindex)
{
	for (int i = 0; i < startindex - 1; i++)
		head = head->next;

	for (int i = 0; i < deleteindex-1; i++)
		head = head->next;
	cout << "出列的序号为: " << head->next->data << endl;
	listnode * p;
	p = head->next;
	head->next = p->next;
	free(p);

	return head;
}

int main(){
	int personnum, starindex, interval;
	cout << "请输入有多少人?" << endl;
	cin >> personnum;
	cout << "请输入从第几个人开始计数" << endl;
	cin >> starindex;
	cout << "请输入间隔为?" << endl;
	cin >> interval;

	listnode * lnvar = creat_circularlist(personnum);
	while (personnum--)
	{
		lnvar = deletenode(lnvar, starindex, interval);
	}

	system("pause");
	return 0;
}

运行结果如图:
约瑟夫环问题循环链表实现_第1张图片

你可能感兴趣的:(c/c++)