其他分享
首页 > 其他分享> > 数据结构(C语言)约瑟夫环

数据结构(C语言)约瑟夫环

作者:互联网

本文采用循环单链表写约瑟夫环,点击可直接链接到之前发的"clist.h"

头文件

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include"clist.h"

约瑟夫环函数

int JosephRing(CList plist)
{
	assert(plist != NULL);
	if (plist == NULL || plist->next == plist)
	{
		return -1;
	}
	CNode* p = plist;
	int count = 0;
	while (plist->next->next != plist)
	{
		p = p->next;
		if (p == plist)//跳过头结点
		{
			p = p->next;
		}
		count++;
		if (count == 2)
		{
			CNode* q = p->next;
			if (q == plist)//跳过头结点
			{
				q = plist->next;
				plist->next = q->next;
			}
			else
			{
				p->next = q->next;
			}
			free(q);
			count = 0;
		}
	}
	return plist->next->data;
}

主函数测试

int main()
{
	CNode head;
	InitList(&head);
	for (int i = 1; i <= 1; i++)
	{
		Insert_head(&head, i);
	}

	printf("%d  ", JosephRing(&head));

	return 0;
}

标签:count,head,include,C语言,int,约瑟夫,next,数据结构,plist
来源: https://blog.csdn.net/Mu_Muxi_/article/details/121303685