单链表实现约瑟夫环(JosephCircle)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/better12038/article/details/82661635
#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;
}

猜你喜欢

转载自blog.csdn.net/better12038/article/details/82661635