数据结构(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;
}
上一篇:基础数据结构-单链表


下一篇:数据结构-单链表基本操作带图完整详解