数据结构约瑟夫环数组解决

有没有人比较懂c需要和数据结构的,有问题想咨询,可赏

img

img


就是想了解一下这个关于约瑟夫环代码的步骤思路,希望有人解答

回答:没有给出代码哈,我这边也不是很好调试,但是有一个问题的是,你这个建环的时候有些复杂感觉,总感觉看不太懂,你试试采用头插法形成链表后,再去将尾指针的next指向头指针,后面的输出序列倒是没啥问题;
创建环代码示例为:

# include <stdio.h>
# include <stdlib.h>
# include "status.h"

typedef int Type;

struct LinkedList
{
    Type data;
    LinkedList* next;
};

// 采用头插法建立链表
void CreateList_Head(LinkedList* head, Type arr[], int length);

// 采用尾插法建立链表
void CreateList_Tail(LinkedList* head, Type arr[], int length);

// 合并两个链表 
void MergeList(LinkedList* headL, LinkedList* headK);

// 打印链表 
void PrintList(LinkedList* head);

int main()
{
    LinkedList* headL = (LinkedList*)malloc(sizeof(LinkedList));
    LinkedList* headK = (LinkedList*)malloc(sizeof(LinkedList));
    headL->next = NULL;
    headK->next = NULL;

    Type arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };
    int length = sizeof(arr) / sizeof(Type);
    
    CreateList_Tail(headL, arr, length);
    CreateList_Tail(headK, arr, length);
    MergeList(headL, headK);
    
    PrintList(headL);
}

void CreateList_Head(LinkedList* head, Type arr[], int length)
{
    int i;
    for (i = 0; i < length; i++)
    {
        LinkedList* newNode = (LinkedList*)malloc(sizeof(LinkedList));
        newNode->data = arr[i];
        newNode->next = head->next;
        head->next = newNode;
    }
    
    LinkedList* cur = head->next;
    while (cur->next != NULL)
    {
        cur = cur->next;
    }
    cur->next = head->next;
}

void CreateList_Tail(LinkedList* head, Type arr[], int length)
{
    LinkedList* cur = head;
    int i;
    for (i = 0; i < length; i++)
    {
        LinkedList* newNode = (LinkedList*)malloc(sizeof(LinkedList));
        newNode->data = arr[i];
        cur->next = newNode;
        newNode->next = NULL;
        cur = cur->next;
    }
    
    cur = head->next;
    while (cur->next != NULL)
    {
        cur = cur->next;
    }
    cur->next = head->next;
}

void MergeList(LinkedList* headL, LinkedList* headK)
{
    LinkedList* curL = headL->next;
    while (curL->next != headL->next)
    {
        curL = curL->next;
    }
    LinkedList* curK = headK->next;
    while (curK->next != headK->next)
    {
        curK = curK->next;
    }
    
    curL->next = headK->next;
    curK->next = headL->next;
    free(headK);
}

void PrintList(LinkedList* head)
{
    LinkedList* cur = head->next;
    while (cur->next != head->next)
    {
        printf("%d ", cur->data);
        cur = cur->next;
    }
    printf("%d ", cur->data);
    printf("\n");
}

哪里不懂???