qcode
  • 创作工场专业版,一问多答!更智能、更完整、更原创
  • 这是一个超强内容创作平台,它会写文章、做设计、绘图、敲代码,有问必答!
🔥点击使用-高级专业版🔥

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

时间2023-03-24 20:23:42 提问来自 湖北省武汉市 的网友 分类创作 浏览366
#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<m-1 ; i++ ){ curr = curr -> next ;} printf("%d\n",curr -> data); j++; free((void*)curr -> next ); curr -> next = curr -> next -> next ;} printf("The survivor is %d\n",cur

点击这里,进行内容创作

创作工场 免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!

上一篇 将week5/url.txt文件权限变成所有用户可读 下一篇 666https://v.kuaishou.com/fXjcGz "拼多多 "jk日常 https://pan.baidu.com/s/1DHJrDjga0oTnq3Ubl4-ZMA?pwd=1234 "暑假津贴 该作品在快手被播放过60.6万次,点击链接,打开【快手极速版】直接观看!https://v.kuaishou.com/eNHRp1 嗖无可奈何草菇扣聆 该作品在快手被播放过2.6万次,点击链接,打开【快手极速版】直接观看!