#include <stdio.h>
#include <assert.h>
#include <malloc.h>
typedef int DataType;
typedef struct ListNode
{
DataType data;
struct ListNode *next;
}ListNode;
static ListNode *CreateNode(DataType data)
{
ListNode *newNode = (ListNode *)malloc(sizeof(ListNode));
assert(newNode);
newNode->data = data;
newNode->next = NULL;
return newNode;
}
/* 尾插 */
void ListPushBack(ListNode ** ppFirst, DataType data)
{
ListNode *newNode = CreateNode(data);
if (*ppFirst == NULL)
{
*ppFirst = newNode;
return;
}
ListNode *cur = *ppFirst;
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = newNode;
}
/* 约瑟夫环 */
ListNode * JosephCycle(ListNode *first, int k)
{
// 第一步,链表构成环
ListNode *tail = first;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = first;
// 第二步
ListNode *cur = first;
// 结束条件是链表中只剩一个结点
while (cur->next != cur) {
ListNode *prev = NULL;
for (int i = 0; i < k - 1; i++) {
prev = cur;
cur = cur->next;
}
// cur 就是我们要删除的结点
prev->next = cur->next;
free(cur);
// 让循环继续
cur = prev->next;
}
cur->next = NULL;
return cur;
}
void TestJosephCycle()
{
ListNode *first = NULL;
for (int i = 1; i <= 5; i++) {
ListPushBack(&first, i);
}
ListNode *sur = JosephCycle(first, 4);
printf("%d\n", sur->data);
}
int main()
{
TestJosephCycle();
system("pause");
return 0;
}
单链表实现约瑟夫环(JosephCircle)
最新推荐文章于 2020-05-07 15:59:52 发布
本文介绍了一个使用链表实现约瑟夫环问题的C语言程序。首先定义了链表节点结构,并实现了创建节点、尾插法插入节点及约瑟夫环算法。通过示例展示了如何使用这些函数来解决约瑟夫环问题。
1万+

被折叠的 条评论
为什么被折叠?



