aiaiask.com©

开花即结果 提问即答案

用C语言创建一个单循环链表解决josephus问题
原始问题:

用C语言创建一个单循环链表解决josephus问题

include <stdio.h>

include <stdlib.h>

/ A linked list node /
struct Node
{

int data; 
struct Node *next; 

};

/ Function to create a new node with given data / //创建一个新节点,并将其data设置为指定的值。

struct Node newNode(int data) //函数返回一个指向新分配的节点的指针。该节点包含由参数data提供的数据。该函数返回一个Node (struct Node* )类型的值,即新分配的节点的地址。

{ struct Node node = (struct Node)malloc(sizeof(struct Node)); // 在内存中使用 malloc() 函数动态地分配内存,以便在其中存储新分配的节点。我们使用 sizeof() 运算符来获取要分配内存大小(即大小Node)

node->data = data; //将data成员变量设为传入参数所代表的特定值。

node->next = NULL;//将next成员变量设为NULL,因为此时尚未连接任何其他节点。

return node;// 返回node所指向新分配的内存区域地址作为函数返回值。该函数返回一个Node (struct Node )类型的值,即新分配的节点在内存中所处位置对应地址信息。 }

/ Function to insert a new_node in a list. Note that this function // 此函數用于將斷開連接得創造得new_node連上已有得linked list中去,注意此function不是return任何東東,而是直接修正原list,也就是說此function是void type. / void insert(struct Node *head_ref, struct Node new_node) { /1. check if the given head_ref is NULL and make the new node as head/ if (head_ref == NULL) {head_ref = new_node;} else { / 2. Else traverse till the last node / struct Node last = head_ref; while (last->next != NULL) last = last->next; / 3. Change the next of last node / last->next = new_node; } } / Function to print linked list/ void printList(struct Node head) { while (head != NULL){ printf("%d ", head->data); head= head->next;} } int josephusLoop(int m, int n){ int i,j=0; struct Node curr=NULL; for (i=1 ; i<=n ; i++){ insert(&curr ,newNode(i));} curr=curr->next ; while (curr!=curr -> next ){ for (i=1 ; i next ;} printf("%d
",curr -> data); j++; free((void*)curr -> next ); curr -> next = curr -> next -> next ;} printf("The survivor is %d
",cur

用C语言创建一个单循环链表解决josephus问题
https://www.aiaiask.com/ask/3293.html
AI / 模型iFLYTEK
时间 / DATEMarch 24, 2023, 8:23 PM
语言zh-CN
IP / 区域湖北 武汉