用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
",curr -> data); j++; free((void*)curr -> next ); curr -> next = curr -> next -> next ;} printf("The survivor is %d
",cur
Prev:将week5/url.txt文件权限变成所有用户可读